Search code examples
javascriptjquerydatatable

Datatables jQuery event works on second page, not on rest


I have made the following jQuery event which actually works when you paginate on the second page.

However it does not trigger on the third and rest of pages, no console.log errors.

Issue obviously lies on the DOM reconstruction over DataTable initComplete parameters which I guess are being applied only for the first results datatable, that is why it only calls my status_icons() function on the second results page and not the rest.

My global function which triggers for DataTable's pagination on click event

function status_icons() {

    $('table tr').each(function() {
        if ($(this).find('td').eq(0).text() == '1') {
            $(this).find('td').eq(0).replaceWith('<i class="fa fa-3 fa-check-circle-o datatable-paid-1" aria-hidden="true"></i>');
            $(this).find('.btn-success').eq(0).prop("disabled", true);
            $(this).find('.btn-success').eq(0).text('Paid'); 
        } else {
            $(this).find('td').eq(0).replaceWith('<i class="fa fa-3 fa-exclamation-circle datatable-paid-0" aria-hidden="true"></i>');
        }
    });
}

This is how I construct my DataTable, calling above function for first results page and the rest

setTimeout(function() {
    $('#invoices-table').DataTable({
        responsive: true,
        columnDefs: [{ orderable: false, targets: [-1, -2, -3] }],
        "lengthMenu": [
            [100, 5, 25, 50, -1],
            [100, 5, 25, 50, "All"]
        ],
        dom: 'Bfrtip',  

        initComplete: function() {
            status_icons() // it executes my function for the first page of results
            var api = this.api();
            // some irrelevant code that uses api and does not cause my issue
            // ...

            $('.paginate_button').on('click', function() {
                status_icons(); // it executes for the second page but not for the rest
            });

        }
    });
}, 3000);

Using

https://cdn.datatables.net/1.10.10/js/jquery.dataTables.js


Solution

  • Those pagination buttons are redrawn...
    So consider them as "dynamic".

    The event "delegation" is needed here.

    Use $(document).on('click','.paginate_button', function() { to start the lookup from a static element which will delegate the events to its actual matching childs.

    CodePen ;)