I have added this link for adding new row to my form:
<a id="add" style="color:white">New row</a>
And here is the jQuery code:
$(document).ready(function(){
var i = 1;
if(i == 1){
$('#add').click(function(){
i ;
$('#dynamic_field').append("HERE GOES THE ROW ELEMENTS");
});
}
});
And it works fine.
But I need to determine that add new row only one time and not several times.
So I tried checking if(i == 1){
in the jQuery, but does not seem to be working and user still can adds new row multiple times.
So how can I limit this to only one time?
CodePudding user response:
you need to use one with click event:
$(document).ready(function(){
$('#add').one('click', function(){
$('#dynamic_field').append("HERE GOES THE ROW ELEMENTS");
});
});
This will invoke click event only once.
CodePudding user response:
Kiran 's answer, which is the better approach in my opinion, but I tried to extend your code with n times.
const unbindEventWithParam = (n, fn) => {
let i = 0
function addRow(event){
console.log('event is running')
i
fn()
if(i == n) return $(this).off(event.type)
}
return addRow
}
const addRow = unbindEventWithParam(2, function(){
$('#dynamic_field').append("add row 1 ")
})
const addRow1 = unbindEventWithParam(4, function(){
$('#dynamic_field1').append("add row 2 ")
})
$('#add').click(addRow)
$('#add1').click(addRow1)
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<a id="add" >New row</a>
<div id="dynamic_field"></div>
<a id="add1" >New row1</a>
<div id="dynamic_field1"></div>
<button id="new-event">New event</button>