tags:

views:

48

answers:

2

I am trying to add a row to a table. I found that we can use the clone() method to duplicate an existing row. My table has two text inputs in it in two different <tr> elements. Cloning the last row is also duplicating the values in my text inputs, which I don't want? How can I clone the row without duplicating the values?

Here's what I have so far:

$("#table-1 tr:last").clone();
+6  A: 

Try this:

var clone = $("#table-1 tr:last").clone().find('input').val('').end();
  • .clone() the last <tr>
  • .find() the <input> elements in the clone
  • set the .val() of the <input> elements to '',
  • call .end() so that the cloned <tr> is stored in the variable instead of the <input> elements.

If you intend to append it to the table immediately, add .insertAfter("#table-1 tr:last") to the end.

var clone = $("#table-1 tr:last").clone().find('input').val('').end().insertAfter("#table-1 tr:last");
patrick dw
:( this is exactly what I answered here : http://stackoverflow.com/questions/3576948/add-row-to-a-table-with-jquery-but-dont-need-its-value/3577015#3577015
Yanick Rochon
@Yanick - That question was a duplicate of this question. This question (and answer) came first, which is why the other one was closed.
patrick dw
+1  A: 

You can add this line after your given line to set the values of the input fields to blank:

$('#table-1 tr:last input').attr('value','');

or just:

$('#table-1 tr:last input').val('');
js1568