Search code examples
jqueryappendclone

Use jquery append to clone hidden html repeatedly


I've got a form and I need to optionally repeat (clone and append to) a big block of form fields over and over.

So, what I've done is put in a hidden div in the page with the code I would want to copy inside, and then I basically want the user to be able to click a button that says "add" and it adds these blank form fields under the last lot for as many times as they want.

The html I want to clone is as follows:

 <div style="display: none;">
        <div class="grab-me">
          <input name="foo[]" />
          <input name="bar[]" />
          <input name="oth[]" />
        </div>
 </div>

The jquery I have at the moment is:

$(function(){
        $('.add-member').live("click", function(e){
            e.preventDefault(e);
            var grab = $('.grab-me');
            grab.appendTo('#register');

        });
    });

But what that is doing is duplicating the form fields on each click of the button. So I click once, it adds the form fields in once as expected. Click the button again, it adds the form fields in twice this time, click again, it adds three sets of form fields in!

I just want it to add the one set of form fields in once, on each click.

Any advice would be really gratefully received!


Solution

  • That's because once it's copied, you then have two .grab-me elements. You should remove the class after cloning the element:

    var grab = $('.grab-me')
        .clone()
        .removeClass('grab-me')
        .appendTo('#register');