1

I have a html table (Bootstrap 3) which has a button in its last td of each row. This button has a class btn-add-row. In my Javascript I use (from this question):

$('.btn-add-row').click(function() {
    var $tr = $(this).closest('tr');
    var $clone = $tr.clone();
    $clone.find('input').val('');
    $tr.after($clone);
});

Now, the row which is cloned also contains that specific button. It copies the button without issue, but when you click the button in the row which was added, the javascript is not executed. The copied button does have the class btn-add-row, and clicking buttons which were originally already on the page still work.

How can I fix this issue?

Community
  • 1
  • 1
B_s
  • 3,026
  • 5
  • 32
  • 51

1 Answers1

2

You have to options here. First to add click handler for cloned row

function clickHandler() {
  var $tr = $(this).closest('tr');
  var $clone = $tr.clone();
  $clone.find('.btn-add-row').click(clickHandler);
  $clone.find('input').val('');
  $tr.after($clone);
}
$('.btn-add-row').click(clickHandler);

And the other to use event delegation

$( "table" ).on( "click", ".btn-add-row", clickHandler);
Viktor Kukurba
  • 1,360
  • 9
  • 14
  • Thanks! This solved my question. I forgot how to add the click handler for a cloned element, so I used your first suggestion which works great. – B_s Feb 11 '16 at 23:53
  • Thats great, but also read about event delegation it has some performance advantageю – Viktor Kukurba Feb 11 '16 at 23:58
  • Thank you for pointing that out. I read through the documentation you provided and I understand event propagation better now. I'll change it in my project. Thank you again! – B_s Feb 12 '16 at 00:03