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
364 views
in Technique[技术] by (71.8m points)

How to Copy Table Row with clone in jquery and create new Unique Ids for the controls

How to Copy Table Row with clone in jquery and create new Unique Ids for the controls.Clone will acually copy data also .i don't want data to be copied .

The table row contains the following information:

<tr> 
     <td><input type="text" id="txtTitle" name="txtTitle"></td> 
     <td><input type="text" id="txtLink" name="txtLink"></td> 
</tr> 

i need to create unique ids for all the new rows ,like txtTitle1, link1 ,Title2,link2 etc

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

You could do something like this:

var i = 1;
$("button").click(function() ???{
  $("table tr:first").clone().find("input").each(function() {
    $(this).val('').attr('id', function(_, id) { return id + i });
  }).end().appendTo("table");
  i++;
})?;?

This would empty the values for new rows and give them unique IDs starting with txtTitle1, txtTile2, etc.

You ca give it a try here. If you needed to change the name too I'd pass an object to .attr() to keep it a bit cleaner, like this:

var i = 1;
$("button").click(function() {
  $("table tr:first").clone().find("input").each(function() {
    $(this).attr({
      'id': function(_, id) { return id + i },
      'name': function(_, name) { return name + i },
      'value': ''               
    });
  }).end().appendTo("table");
  i++;
});?

You can try that version out here.


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

...