Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
338 views
in Technique[技术] by (71.8m points)

jQuery Clone table row

I have a table with an Add button on the end. When you click this button I want a new table row to be created underneath the current one. I also want the input fields on this row to be blank. I am trying to do this using .clone() but it clones all the rows on the page. Please help. Thanks

Script

$("input.tr_clone_add")
        .live('click', function(){
              $(this).closest('.tr_clone')
                    .clone()
                    .insertAfter(".tr_clone")
         });

HTML

<table width="100%" border="0" cellspacing="0" cellpadding="0" id="table-data">
<tr>
<td>Name</td>
<td>Location</td>
<td>From</td>
<td>To</td>
<td>Add</td>
</tr>
<tr class="tr_clone">
<td><input type="text" autofocus placeholder="who" name="who" ></td>
<td><input type="text" autofocus placeholder="location" name="location" ></td>
<td><input type="text" placeholder="Start Date" name="datepicker_start" class="datepicker"></td>
<td><input type="text" placeholder="End Date" name="datepicker_end" class="datepicker"></td>
<td><input type="button" name="add" value="Add" class="tr_clone_add"></td>
</tr>
</table><!-- /table#table-data -->
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Your problem is that your insertAfter:

.insertAfter(".tr_clone")

inserts after every .tr_clone:

the matched set of elements will be inserted after the element(s) specified by this parameter.

You probably just want to use after on the row you're duplicating. And a little .find(':text').val('') will clear the cloned text inputs; something like this:

var $tr    = $(this).closest('.tr_clone');
var $clone = $tr.clone();
$clone.find(':text').val('');
$tr.after($clone);

Demo: http://jsfiddle.net/ambiguous/LAECx/ or for a modern jQuery: http://jsfiddle.net/ambiguous/LAECx/3274/

I'm not sure which input should end up with the focus so I've left that alone.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...