Question

I have a JQuery Datatable that is redrawn each time I click on a chart item.

I was using .on() to capture the click event, which was great in capturing the click events on all the rows, including those not currently in the DOM (i.e. not on page 1). However, although the click event is caught, I can't seem to access the data in the click event once the datatable was redrawn. Here is the code that is included in the AJAX .success function:

ajax_call()
    .success(function (data) {
        ...
        var table = $('#datatable').DataTable({...});
        ...
        $('#datatable tbody').on( 'click', 'tr', function () {
            var d = table.row( this ).data();
        });
    });

The error: TypeError: d is undefined

So I tried the bind('click', ...) catch:

$('#datatable tbody tr').bind( 'click', function () {
    var d = table.row( this ).data();
});

But this only catches click events from the rows in the DOM (i.e. 1st page).

So how should I catch the click events from all pages even if the datatable is redrawn in an AJAX .success function?

Was it helpful?

Solution

The answer to this is to 'unbind' the .on() click event before re-initialising the table using .off() method. Multiple bound events on elements cause the data and bindings to be stacked.

So simply something like:

ajax_call().success(function (data) {
    ...
    $('#datatable tbody').off( 'click', 'tr');
    var table = $('#datatable').DataTable({...});
    ...
    $('#datatable tbody').on( 'click', 'tr', function () {
        var d = table.row( this ).data();
    });
});

OTHER TIPS

You can try binding your click event on the table container and in the event handler, check if the clicked target is the hotspot you are looking for:

$('#datatable_container').bind( 'click', function (event) {
    var $target = $(event.target);
    if($target.prop("tagName") == "TR") {
       //Do something
       //...
    }
});

Since I can't see your source, I'm assuming it looks something like this:

<div id="datatable_container">
    <table id="datatable">...</table>
</div>

I made a Plunker showing what I mean. Hopefully it helps.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top