开发者

How to duplicate and clear a form element using jQuery?

If I have the following html within a 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 do I go about creating a copy of this (first) 'row', with the value stripped out, so as to append thereafter as desired, for multiple user entries. The reason why a value may exist already (as in this example) is for cases where data is being edited. I would like to obtain:

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

I have thought along the lines of:

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

but this does not开发者_StackOverflow社区 work in that it does not seem to remove the values, nor does it capture the outer html (the wrapper).

Can anyone advise?

Thank you.


You have a syntax error in your js. .find('.row:first-child) should be .find('.row:first-child'), but as for cloning, the default behavior is to strip out the values. scratch that... that's only 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)
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜