Question

Want to copy the first or last row in a specific, named table. I have a large number of columns therefore cloning is the best way to go. I found this code snippet:

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++;
})​;​

My problem is, where do change the selector to specify the table that I am looking for? If you take a look at this fiddle you'll note that adding a row does add to only one table, but it appears to clone the row from the first available table. Say I only want to copy rows from table1 because I am appending to table1. How do I go about doing this?

Was it helpful?

Solution

Updated code example with from (#table1) and to (#table2) tables defined.

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

OTHER TIPS

Try this :

Append row for the "table" with id table "table1" :

$("button").click(function() ​​​{
  $("#table1 tr:first").clone().find("input").each(function() {
    $(this).val('').attr('id', function(_, id) { return id + i });
  }).end().appendTo("#table1");
  i++;
})​;​

Append row for the "table" with id table "table2" :

$("button").click(function() ​​​{
  $("#table2 tr:first").clone().find("input").each(function() {
    $(this).val('').attr('id', function(_, id) { return id + i });
  }).end().appendTo("#table2");
  i++;
})​;​
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top