When you want to have user selectable rows in DataTables, it is relatively trivial when using DOM based data - but when using server-side processing, DataTables doesn't retain DOM row elements over pages / filtering etc. As such, you will need to keep a track of which rows a user as selected and mark them as selected on each draw.
This is shown in this demo, which uses a unique ID assigned to the TR element (this is done
automatically through the use of the DT_RowId
special property returned as part of the
object given by the server for each row) to track which rows are selected and reselect them is
appropriate on a draw.
First name | Last name | Position | Office | Start date | Salary |
---|---|---|---|---|---|
First name | Last name | Position | Office | Start date | Salary |
The Javascript shown below is used to initialise the table shown in this example:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 | $(document).ready(function() { var selected = []; $("#example").dataTable({ "processing": true, "serverSide": true, "ajax": "scripts/ids-arrays.php", "rowCallback": function( row, data ) { if ( $.inArray(data.DT_RowId, selected) !== -1 ) { $(row).addClass('selected'); } } }); $('#example tbody').on('click', 'tr', function () { var id = this.id; var index = $.inArray(id, selected); if ( index === -1 ) { selected.push( id ); } else { selected.splice( index, 1 ); } $(this).toggleClass('selected'); } ); } ); |
In addition to the above code, the following Javascript library files are loaded for use in this example: