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
  • 5,161
  • 8
  • 54
  • 91

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,897
  • 3
  • 22
  • 31
1

Try like this..

$(function() {
  $(document).on("click", "#tblTest > tbody > tr", function(e) {
    alert();
  });
});
Ionut
  • 10,249
  • 4
  • 33
  • 62
Hikmat Sijapati
  • 6,557
  • 1
  • 7
  • 18
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
  • 10,249
  • 4
  • 33
  • 62
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
  • 3,904
  • 1
  • 11
  • 31
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