Search code examples
jqueryhtml-tablerowclone

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

Solution

  • 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);
    });