How can I select() a row within a draw callback
How can I select() a row within a draw callback
When initializing a table, I'm trying to highlight a row whose id field value matches a stored cookie value. I'm trying to do this via either the createdRow() or initComplete() callbacks. I can specify the row via its index. I can then use the rows() api to, for example, retrieve the row data. However, when I try to use select() on the row it generates an error:
var table = $('#myTable').DataTable(
.
.
.,
'initComplete': function(){
//...get the index of the row, e.g. 1
var api = this.api();
console.log(api.rows(1).data()); // Object[Object { field_id_59="2", field_id_60="Some data"}]
api.rows(1).select();
}
}
The final statement generates the error "TypeError: a._select is undefined
e.each(c.aanFeatures.i,function(c,a){var a=e(a),d=a.children("span.select-info")..."
Once the table has been drawn (by commenting out the offending statement), Select() is working fine--records get highlighted on clicks and I can work with the Select and Deselect events.
Perhaps I need to directly add a "Success" class to the row node?
Many thanks in advance.
This question has an accepted answers - jump to answer
Answers
Okay, If I add the class manually ('selected', not 'success'), the row is correctly highlighted when the table is first drawn. But this doesn't get registered with Select(). Thus, if row 0 is initially highlighted, and I click on row 1, both rows are highlighted ("Select" is initialized as "single"). I can then manually deselect row 0 by clicking on it, and single select works on the table henceforth.
So it seems I do indeed need to achieve the initial highlighting via Select().
SOLVED: did the selection after the table was initialized:
(Leaving this here, in case anyone has the same problem)
When I switched to an AJAX data source, the above code stopped working--table.rows() was being called before the ajax data was returned, so select() didn't see the data and hence didn't select anything. So I wrapped the function in a timer as follows:
The timer debugging code indicated that the function waited 300 msec before executing. Anyway, solved the problem!
I know you answered your own comment, but I would have suggested using a rowCallback.
https://datatables.net/reference/option/rowCallback
You don't have to worry about any timing when done this way.