0

I am trying to trigger a custom event when new rows are added to the table. Below is the code I am using but the event is not firing.

 <!DOCTYPE html>
    <html lang="en">
       <head>
          <script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
       </head>
       <body>
          <div id="container">first div</div>
          <script>
             $( document ).ready(function() {    
             $( "table#t-result-data tbody" ).on( "update", function() {
               console.log('tr id' );
             });

             function appendToTable() {
                 var htmlStr;     
                 htmlStr = "<table id='t-result-data'><tbody><tr><td>First Row First column</td></tr></tbody></table>";                      
                    $("#container").html(htmlStr)
                    $('table#t-result-data').trigger('update');
                  }
               appendToTable();    
               });

          </script>   
       </body>
    </html>

What am I doing wrong. The table and its rows are dynamically added

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
RJD
  • 135
  • 3
  • 14

1 Answers1

1

Your code is almost there but has two issues.

Firstly, you're attaching the event handler before the element exists in the DOM. You need to use a delegated event handler to solve this.

Secondly, you trigger the event on the #t-result-data element, yet listen for it on the tbody. This needs to be consistent.

With those issues addressed, the code works fine:

$(document).ready(function() {
  $(document).on('update', 'table#t-result-data', function() {
    console.log('tr id');
  });

  function appendToTable() {
    var htmlStr = '<table id="t-result-data"><tbody><tr><td>First Row First column</td></tr></tbody></table>';
    $('#container').html(htmlStr)
    $('table#t-result-data').trigger('update');
  }
  appendToTable();
});
<script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
<div id="container">first div</div>
Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339