Click event can't access table row data after reload
Click event can't access table row data after reload
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, or access the row data, from all pages even if the datatable is redrawn in an AJAX .success function?
Answers
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: