0

I have an example here with table where rows are dynamically added. Each row should trigger event:

  $("#tblTest > tbody > tr").on("click", function(e){    
    alert();        
  });

This code doesn't work for dynamically added rows. What is the problem?

FrenkyB
  • 6,625
  • 14
  • 67
  • 114

6 Answers6

3

It is adding the click to the tr on creation. You need to instead attack the click to the tbody then filter to tr.

  $("#tblTest > tbody").on("click", "tr", function(e){    
    alert();        
  });
Tom
  • 1,971
  • 3
  • 22
  • 32
1

Try like this..

$(function() {
  $(document).on("click", "#tblTest > tbody > tr", function(e) {
    alert();
  });
});
Ionut Necula
  • 11,107
  • 4
  • 45
  • 69
Hikmat Sijapati
  • 6,869
  • 1
  • 9
  • 19
1

You should change your code to use the Body for the .on event:

  $("body").on("click", "#tblTest > tbody > tr", function(e){    
    alert();        
  });
1

For dinamically added elements you need to use event delegation:

$(document).on("click", "#tblTest > tbody > tr", function(e){    
    alert('test');        
  });

Updated Codepen.

Ionut Necula
  • 11,107
  • 4
  • 45
  • 69
1

When you dynamically add a row, you must bind a new onClick listener to the added element. Your code only adds the listener to elements already on the page; not newly created elements. Something like this will work fine:

var AddRow = function(){
     // add element
     $("#tblTest > tbody").append("<tr><td>Test name</td><td>Last anme</td></tr>");
     // add listener to new element
     $("#tblTest > tbody > tr:last-of-type").on("click", function(e){    
          alert();        
     });
}

the :last-of-type psuedo-selector is key to avoid binding multiple listeners to the cells.

treyhakanson
  • 4,611
  • 2
  • 16
  • 33
0

You can use event delegation.

 $(document).off('click.namespace').on('click.namespace', '#tblTest > tbody > tr', function (e) {
alert();           
  });

It will rebind the Events. So dynamically appended rows also bind with events.

rajiv
  • 64
  • 1
  • 6