Skip to content
Advertisement

How to limit jQuery appending to form

I have added this link for adding new row to my form:

<a id="add" class="btn btn-info" 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?

Advertisement

Answer

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.

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement