Reputation:
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
Upvotes: 35
Views: 60909
Reputation: 630379
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.
Upvotes: 82