0

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?

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Shrout1
  • 2,497
  • 4
  • 42
  • 65

2 Answers2

1

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++;
})​;​
prothid
  • 616
  • 4
  • 11
  • Thanks a million! Your syntax for finding a specific row in a specific table worked *great*! `$("table#table1 tr:first").clone()`. Exactly what I needed! – Shrout1 Jun 09 '13 at 13:33
1

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++;
})​;​
  • Thanks for trying to help! The syntax for uniquely identifying a specific row from a specific table is as such: `"table#table1 tr:first"`. Very close! You did put me on the right track. – Shrout1 Jun 09 '13 at 13:35