Sunday, July 31, 2016

Datatables events not working on second page

I've revisited the datatables library for jquery. The new 1.10 version has a lot of improvements.

But I immediately ran into some trouble. After the easy zero config initialization I added a select box to one of the cells, and then added a a jquery "on change" event handler to that select box.

The problem is this works on the first page, but fails on subsequent pages, or if the page was ordered or filtered etc. This is specified in the "My events don't work on the second page" section of the Datatables FAQ and basically happens because Datatables manipulates the DOM.

My solution was to re-assign the event handler on each draw event, like this:





var table;

$(document).ready(function () {

    table = $('#example')
        .on('draw.dt', function () {
            handleSelectEvent();
        })

        .DataTable();
});


var handleSelectEvent = function () {
    console.log('in handleselect fn');

    $('#example select').off('change')
        .on('change', function () {

        // do whatever

    });

}


If I didn't specifically unbind the event handler (with the off), the event handler would get loaded loaded on each draw of the table. So I would start with 1 call, but then end up have 2, 3,4 calls each time I did a reorder, pagination search or so on.

Minutes after I fixed this issue, I found another nice slick way to handle this issue here: http://www.gyrocode.com/articles/jquery-datatables-why-click-event-handler-does-not-work/
which basically say you specify a selector as the second argument for the event handler, in this case a CSS class around the select box.

No comments:

Post a Comment