I'm currently using the DataTables plugin for my project.
I have an AJAX sourced datatable where you can only ever have one row selected, now because my datatable is done server-side I need to keep track of which one is selected when changing pages.
Therefore I have been using this solution but this only seems to work for multiple row selection
Now essentially what I want to happen is, when you select a new row it should add the new row id to the array but also remove the previously added row id from the array, so there should only ever be one result in the array at a time.
Visually for better understanding:
var selected = []
Click Row 1 after loading table = [row_1]
Click Row 2 removing row_1 and adding row_2 = [row_2]
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');
} );
CodePudding user response:
Instead of adding an element to the array, you could replace the whole array. It seems a bit wasteful to use an array to store a single element, but there you go.
selected.push( id );
becomes
selected = [id];