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 jquery jquery

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


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.