Search code examples
jqueryclone

JQuery Clone is cloning final row's data


I am running into a problem. I was using:

$(this).parents("tr:first").remove();

to delete the row the user clicked on and then:

var row = $('#picTableDisplay tbody>tr:last').clone(true)
            .insertAfter('#picTableDisplay tbody>tr:last');

to replace a new (empty) row at the bottom of the table.

But, when the table is full (12 rows) and the user wants to remove a row, the bottom table (that has data) gets cloned (with the data).

In this scenario, how do I remove the clicked on row and add a row to the bottom of the table that is empty?

Thanks.


Solution

  • It seems to be doing exactly what you've told it to do... cloning the last row, with or without data.
    The solution is simple - don't do it.

    1. Clone a last invisible row (so you have 13 rows), or
    2. Clone the row from a template you keep on the side, eg:

      $('#RowTemplate tr').clone(true).show() 
      
    3. Another option is to copy the row when the page is loaded, and then recloning it:

      var rowTemplate = $('#picTableDisplay tbody>tr:last').clone(true)
      
      $('#picTableDisplay tr').click(function(){
         $(this).closest('tr').remove();
         var row = rowTemplate.clone(true) //...
      });
      

    Please also note there's a known bug with cloning the last element on IE, as detailed here: Problem using jQuery clone function in form.