clone table row

11,263

You can hookup a live event to all the buttons. If you give them a class of clone for instance the following will work.

$('input.clone').live('click', function(){
   //put jquery this context into a var
   var $btn = $(this);
   //use .closest() to navigate from the buttno to the closest row and clone it
   var $clonedRow = $btn.closest('tr').clone();
   //append the cloned row to end of the table

   //clean ids if you need to
   $clonedRow.find('*').andSelf().filter('[id]').each( function(){
       //clear id or change to something else
       this.id += '_clone';
   });

   //finally append new row to end of table
   $btn.closest('tbody').append( $clonedRow );
});

Please Note: If you have elements in the table row with id's you will need to do a .each through them and set them to a new value otherwise you will end up with duplicate id's in the dom which is not valid and can play havoc with jQuery selectors

You can do this like so

Share:
11,263
mrpatg
Author by

mrpatg

Updated on June 04, 2022

Comments

  • mrpatg
    mrpatg almost 2 years

    How can i use javascript (i assume) to clone a table row like ive beautifully illustrated in the picture below?

    clone row