Use jquery append to re-clone hidden html

I have a form, and I don’t have to repeat (clone and add) a large block of form fields over and over again.

So, what I did is placed in a hidden div on the page with the code that I would like to copy inside, and then I basically want the user to click the button that says “add”, and this adds these fields to an empty form under the last lot as many times as he wants.

I want to clone html as follows:

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

In the jquery that I have, there is:

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

But what he does is duplicate the form fields each time the button is clicked. So I click once, it adds form fields as early as possible. Click the button again, it adds form fields twice this time, click again, adds three sets of form fields!

I just want it to add one set of form fields once, each time it is clicked.

Any advice would be greatly appreciated!

+4
source share
3 answers

What, because after copying it, you have two .grab-me elements. You must remove the class after cloning the element:

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

There are a few things you can do, the easiest one that comes to my mind is to add a call to .first ():

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

The problem you are having is to add it the first time you finish with two divs that have a .grab-me class, so your jquery captures both.

0
source

$ ('. grab-me'). eq (0) to get only one form (first form with grab-me class)

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

All Articles