jQuery DataTables: Custom control does not work on second page and after

Problem

Cause

jQuery DataTables keeps only one page in DOM for performance reasons. When table is initialized only the first page exists in DOM.

That is why selector $('span.rating') returns first page elements only. In the example above star rating plug-in does not work on second page and after.

Solution 1: Using createdRow

Custom control can be initialized when jQuery DataTables creates a row. This could be done in a callback function defined using createdRow option.

If you are using client-side processing mode and have many rows, consider enabling deferred rendering using deferRender option (deferRender: true). This will improve performance by initializing only visible rows.


var table = $('#example').DataTable({
    // ... skipped ...
    createdRow: function(row, data, dataIndex){
       // Initialize custom control
       $('span.rating', row).raty({
          // ... skipped ...
       });
    }
});

Solution 2: Using initComplete

If you are using client-side processing mode, custom control can be initialized after the data has been fully loaded using initComplete option.

This solution will work only in client-side processing mode with disabled deferred rendering.


var table = $('#example').DataTable({
    // ... skipped ...
    initComplete: function(settings){
        var api = new $.fn.dataTable.Api( settings );
            
        // Initialize custom control
        $('span.rating', api.rows().nodes()).raty({
            // ... skipped ...
        });
    }
});

Events

In order to handle events from your custom control you need to use delegated event handler.

For example:


$('#example').on('click', 'span.rating', function(e){
   // ... skipped ...
});

Please see jQuery DataTables: Why click event handler does not work or DOM / jQuery events for more details.

Responsive extension

If you use Responsive extension and your custom control is located in a column that may be hidden on smaller screens, there is more code to be added. Please see jQuery DataTables: Responsive extension and custom controls for more details.

Recommended For You

Books

Online Courses

You Might Also Like

Comments

  1. Hi, I ran into this and solved by letting the elements I needed to act upon share a css class. Then when an item of that class is clicked, deriving it’s Id. Maybe a hack I don’t know but it works for my purposes so far. Best.

Leave a Reply

You may use simple HTML to add links or lists to your comment. Also use <pre><code class="language-*">...</code></pre> to mark up code snippets. We support language-js, language-markup and language-css for comments.
(Optional)