How can I add a custom click event for some of the table headers in the datatable. I have removed the default sorting event from every column except 1st column. So I want to add the custom event to those columns. And I want to find the index of the column the user clicked.
What I have tried so far is this. But I can't figure out how to find the index of the column user clicked.
var table = $('#example').dataTable( {
"data": data_set,
"columns": column_titles,
"columnDefs": column_defs
} );
$('#example thead').on( 'click', 'th', function () {
alert( 'Column clicked on: ');
} );
P.S. I have found this article https://datatables.net/reference/api/column().header() and followed it. But when I call table.cell() , it gives an error.
$('#example tbody').on( 'click', 'td', function () {
var idx = table.cell( this ).index().column;
var title = table.column( idx ).header();
alert( 'Column title clicked on: '+$(title).html() );
} );
var table = $(`#mytable`).DataTable({
...
});
var headers = table.columns().header().toArray();
$(headers).on('click', function () {
// do something
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With