skip to Main Content

I have a dynamic datatable where data are loaded by Ajax.
My HTML is:

<table id="dynamic_table"></table>

and the JS is:

$(document).ready(function() {
        $('#dynamic_table').DataTable( {
            "ajax": '/ajax_handler',
            ...
$('td').on('click', function(e){
    alert("I'm td")
});
$('body').on('click', function(e){
    alert("I'm body")
});

Well ‘body’ is caught but ‘td’ is not. Of course the browser shows rows with their tr/td tags but it seems like that (dynamic) loaded data aren’t still seen by the JS.

How I can catch clicks to my dynamic td? How I can bind them?

2

Answers


  1. The problem you are running into is your DataTable create td elements after you bind those click events. There are 2 alternatives, re bind all event listenes to TD after table renders, or using event bubbling to capturate click event to parent component.
    There is a jQuery on() argument you can pass to tell the table listen for click events.

    $('table').on('click', 'td', function(e){
        alert("I'm td")
    });
    
    Login or Signup to reply.
  2. Assign class to td and bind event handler to this class.

    $.on(‘event.js-name’, function(){});

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search