Reputation: 317
I have a datatable which when I click on a row, it highlights the row. I want to save the row index and use it to re-highlight that row when the page is reloaded.
var table = $('#example').DataTable( {
"ajax": "DataQueries/FetchOpenJobs.asp",
stateSave: true,
"aLengthMenu": [[10, 25, 50, 100], [10, 25, 50, 100]],
"iDisplayLength": 25,
"order": [[ 0, "desc" ]],
columnDefs: [
{"visible": false, "targets": [2,3]},
{"type": 'date-uk', "targets": [1,9,10] },
{"type": 'title-string', "targets": [11] }
],
} );
I am able to get the row index using the below:
var selectedRowIndex = table.row(this).index();
However, I am unsure as to how to re-highlight using the row index.
Upvotes: 2
Views: 5040
Reputation: 85518
I think this question deserves a more thorough example.
I would save the selected id
('s) in the localStorage
as an stringified array. When the page is (re)loaded then retrieve the array and if it contains any stored indexes, highlight the corresponding rows. Below a code example in explanatory order :
Sample code of highlightning rows when they are clicked :
$('#example').on('click', 'tr', function() {
$(this).toggleClass('highlight');
processSelected(table.row(this).index(), $(this).hasClass('highlight'));
});
Basic code for maintaining an array of highlighted row indexes in the localStorage :
function processSelected(id, selected) {
if (selected) {
selectedRows.push(id);
} else {
selectedRows.splice(selectedRows.indexOf(id), 1);
}
localStorage.setItem('selectedRows', JSON.stringify(selectedRows));
}
When the page is loaded, retrieve the array from localStorage :
var selectedRows = JSON.parse(localStorage.getItem('selectedRows'));
Finally, re-highlight stored row indexes when the dataTable is initialised :
var table = $('#example').DataTable({
initComplete : function() {
if (!Array.isArray(selectedRows)) {
//selectedRows does not exists in localStorage or is messed up
selectedRows = [];
} else {
var _table = this.api();
selectedRows.forEach(function(index) {
//for some reason to$() doesnt work here
$(_table.row(index).node()).addClass('highlight');
})
}
}
});
demo -> http://jsfiddle.net/f3ghvz4n/
Try the demo, highlight some rows and then reload the page. Notice that this works on a paginated dataTable as well!
Update. When you are using a AJAX datasrc reloaded each 30 secs, I think you could skip the initComplete
and just rely on the draw.dt
event :
var table = $('#example').DataTable();
$('#example').on('draw.dt', function() {
if (!Array.isArray(selectedRows)) {
selectedRows = [];
} else {
selectedRows.forEach(function(index) {
$(table.row(index).node()).addClass('highlight');
})
}
})
Completely untested, but cannot see why it shouldnt work.
Upvotes: 2
Reputation: 7117
This should do the trick:
$('#id tbody > tr').eq(rowindex)
or
$('#id tbody > tr').eq(rowindex).children().addClass('myClass');
Upvotes: 0