How to duplicate and clear form element using jQuery?

If I have the following html inside the form:

<div class='example'> <div class='row'> <input name='first_field' type='text' value='Hello' /> <input name='second_field' type='text' value='World!' /> </div> </div> 

How can I create a copy of this (first) β€œline”, with a highlighted value, so that if necessary I can add several user entries to it. The reason a value may already exist (as in this example) applies to cases where data is being edited. I would like to get:

  <div class='row'> <input name='first_field' type='text' value='' /> <input name='second_field' type='text' value='' /> </div> 

I thought line by line:

 var row = $('.example').find('.row:first-child').clone(); row.find('[name]').each(function() { $(this).val(''); }); 

but this does not work because it does not seem to remove the values ​​and capture the external html (wrapper).

Can anyone advise?

Thanks.

+4
source share
1 answer

You have a syntax error in js. .find('.row:first-child) should be .find('.row:first-child') , but as for cloning, the default behavior is to cross out the values. scratch it ... that's just for cloning the actual input elements, apparently.

http://jsfiddle.net/Yb2Ym/

 var row = $('.example').find('.row:first-child').clone(); row.find('[name]').each(function() { $(this).val(''); }); $(".row:last").after(row) 
+2
source

All Articles