On row click event is not getting current selected row data
On row click event is not getting current selected row data
EckhardHerdt
Posts: 1Questions: 1Answers: 0
I have this on a row click in datatables:
$(document.getElementById('table1')).on('click', 'td', function(e) {
var table = $(document.getElementById('table1')).DataTable();
var selectedItem = table.rows( { selected: true } ).data()[0];
console.log(selectedItem)
}
The problem is selectedItem is not getting data of the currently selected row, but the selected before.
What is happening is that on row click event is happening before datatables selection occurs.
How can I fix this? I need the current selected row inside onclick event.
The initialization of datatables is:
$('#table1').dataTable({
destroy: true,
scrollX: true,
searching: true,
lengthChange: true,
pageLength: 5,
lengthMenu: [5, 10, 25, 50, 100],
paging: true,
pagingType: "simple_numbers" ,
info: true,
autoWidth: false,
columnDefs:[ { "defaultContent" : "", "searchable" : true, "className" : "text-left", "targets" : 0},
{ "defaultContent" : "", "searchable" : true, "className" : "text-left", "targets" : 1},
{ "defaultContent" : "", "searchable" : true, "className" : "text-left", "targets" : 2},
{ "defaultContent" : "", "searchable" : true, "className" : "text-right", "targets" : 3},
{ "defaultContent" : "", "searchable" : true, "className" : "text-left", "targets" : 4},
{ "defaultContent" : "", "searchable" : true, "className" : "text-center", "targets" :5},
{ "defaultContent" : "", "searchable" : true, "className" : "text-left", "targets" : 6},
{ "defaultContent" : "", "searchable" : true, "className" : "text-left", "targets" : 7},
{ "defaultContent" : "", "searchable" : true, "className" : "text-left", "targets" : 8}],
select:true ,
columns: [{"data":"id"},{"data":"name"},{"data":"lastName"},{"data":"age"},{"data":"birthDate"},{"data":"isVIP"},{"data":"gender"},{"data":"title"},{"data":"email"}]
});
THANK YOU!
This discussion has been closed.
Answers
Couple of things:
$('#table1') and $(document.getElementById('table1') do the same thing but the same thing. You might look up jquery selectors.
with that said, DataTables has a select event that can be used that is only triggered when a row is selected. Your event will actually fire when a row is being clicked whether it is being selected or unselected.
https://datatables.net/reference/event/select
also your columnDefs can be simplified to
I had the same problem.
I am not really sure that I understood bindrid explanation. But his code works. I believe that the example in https://datatables.net/examples/advanced_init/events_live.html
works because it is an extremely simple table.
$('#table1').on( 'select.dt', function ( e, dt, type, indexes ) {
//whatever
} );
works much better