JONxBLAZE
JONxBLAZE

Reputation: 81

Jquery cloning, inserting and manipulating inserted elements

I'm cloning a table the contains 2 buttons. One button clones and inserts a new table row, and the other button clones the entire table and inserts it after the last table.

When a table has been cloned and inserted at the bottom, I click on the the Add button to add a new row, the row gets inserted at the top table only.

How do I insert a new row in the corresponding table if I have 5 tables?

My HTML:

<table class="myTable">
<tr class="firstRow">
    <td>
        Name: <input type="text" size="30" />
    </td>
    <td>
        Email: <input type="text" size="30" />
    </td>
</tr>
<tr>
    <td colspan="2" align="right">
        <input type="button" value="Add" class="addRow" />
    </td>
</tr>
</table>

<p><input type="button" value="Copy" class="addTable" /></p>

jQuery:

$('.addRow').click(function(){
  var cloned = $('.firstRow').clone(true);
  cloned.insertAfter($('table.myTable tr').eq(-2)).removeClass('firstRow');
});


$('.addTable').click(function(){
  var cloned = $('.myTable').clone(true);
  cloned.insertAfter($('.myTable:last')).before('<hr />').removeClass('myTable');
});

My Fiddle: http://jsfiddle.net/jonxblaze/S3N77/

Upvotes: 1

Views: 2639

Answers (2)

Christopher Ram&#237;rez
Christopher Ram&#237;rez

Reputation: 1720

Your implementation for .addRow button is not good.

Please try this one:

$('.addRow').click(function(){
    var cloned = $(this).parents('table').find('tr:eq(0)').clone(true);
    cloned.insertBefore($(this).parents('table').find('tr:last-child'));
});

The above implementation does not need the .firstRow class. Also it inserts a cloned row only on the table which is parent of the button clicked.

DEMO

Upvotes: 1

Drew Baker
Drew Baker

Reputation: 14430

This is because the second cloned table doesn't exist when you bind the clone row click event. You need to use the jQuery .on() function to do this.

http://api.jquery.com/on/

Basically, when you use .click() it binds that function to all the elements it can find matching the selector, which at document ready, is only one table. .on() works on all elements going forward in time, not just those that exist at the time the script is run.

If you really want to use .click() instead of .on(), re-bind the clicks after you've made the second table.

Here is a post of me having a simalar issue: Using jQuery .on() to make a drop-down menu

Upvotes: 1

Related Questions