rostamiani
rostamiani

Reputation: 3255

How to copy first row of a table using Jquery?

I need to clone first row of table. I added a new button, but nothing happens! #add_button is placed after the table.

(First row is the header)

$('#add_button').click(function(event) {
var new_line = $(this).prev('table').find('tr:eq(1)');
$(this).prev('table').append(new_line);
});

Upvotes: 1

Views: 4306

Answers (2)

Bhushan Kawadkar
Bhushan Kawadkar

Reputation: 28513

You need to clone the table row and then append so that original row will not move, see below code

NOTE - use variable to table element so that you don't have to call prev('table') again to find table and then append. Also this code will work provided that you have table before add_button, there must not be any other element in between.

$('#add_button').click(function(event) {
   var $table = $(this).prev('table');
   var new_line = $table.find('tr:eq(1)').clone();
   $table.append(new_line);
});

Upvotes: 1

Arun P Johny
Arun P Johny

Reputation: 388396

You need to clone else you will be simply moving the existing row

$('#add_button').click(function (event) {
    var $table = $(this).prev('table'),
        $nrow = $table.find('tr:eq(1)').clone();
    $table.append($nrow);
});

Demo: Fiddle

Upvotes: 4

Related Questions