htmljqueryajaxevent-delegation

Detecting click events on appended table rows added via ajax/jQuery


I need to detect click events on rows that are added dynamically to a table (using jQuery). The table has the id myTable.

This is no problem for table rows created at design time/hard coded to the local page; I know I can use $('#myTable tr').click(...);

However, my use case is loading new table rows via ajax and appending it to the table. In this situation, the click event handler is not called.

In the past I used jQuery's .live() function for handling dynamically loaded elements, but I see that has been deprecated now in favour of .on(). This would be fine, except that it is not working for me in this situation.

Here is some demonstration code and a jsfiddle that shows the issue. Notice that clicking on 'Static row' displays an alert box, as intended, yet this does not happen for the dynamically added rows:

<!DOCTYPE html>
<body>
  <h1>Dynamic table event test</h1>
  <table id="myTable">
  <tr><td>Static row</td></tr>
  </table>
  <button onclick="addTableRow()">Add row</button>
  <script>
    function addTableRow() {
        $('#myTable').append('<tr><td>Dynamic row</td></tr>');
    }
    $('#myTable tr').on('click', function() {
      alert('Row clicked');
    });
  </script>
</body>
</html> 

Solution

  • Change

    $('#myTable tr').click(...);
    

    to

    $('#myTable').on('click', 'tr', function() { ... });
    

    The first creates only eventhandelrs for elements matching your selector and attaching it to those elements that are present during load. The second attaches the handler to the parent table instead.