user1917037
user1917037

Reputation: 23

How to clone tr in table using jquery

Have a lot of tables on the page. I want to add new row with existing data after some one tr. So I have one of the table:

        <table>
            <tr>
                <th>...</th>
                <td>...</td>
            </tr>
        </table>
        <p id="add-tr">[add]</p>

And when I click to [add], I want to add a new tr with existing th and td elements. I found last table with:

$('#add-tr').on('click',function(){
    $(this).prev('table')...;
    });

(checked with hide() func) What to do next? Tried:

$(this).prev('table').closest('tr').clone();

But no effect!

My first question at stackoverflow! So not too harsh, and thanks!

Upvotes: 2

Views: 4374

Answers (3)

Syon
Syon

Reputation: 1614

You were really close, just need to select the tr inside using .find() not .closest(), then choose where to .appendTo():

$('#add-tr').on('click',function(){
    $(this).prev('table').find('tr').first().clone().appendTo('table');
});​

Upvotes: 1

orolo
orolo

Reputation: 3951

I think you have it cloned right but now you need to actually append it:

var myRow = $(this).prev('table').closest('tr').clone();

$(this).prev('table').closest('tr').append(myRow);

or similar

Upvotes: 0

Ram
Ram

Reputation: 144689

You should use find or children method and append the row, closest method selects the closest parent of the element.

var $table = $(this).prev('table');
$table.find('tr:first').clone().appendTo($table);

Upvotes: 5

Related Questions