Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery dataTables header click custom event

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() );
 } );
like image 514
Maduranga Siriwardena Avatar asked Dec 25 '14 17:12

Maduranga Siriwardena


1 Answers

var table = $(`#mytable`).DataTable({
    ...
});

var headers = table.columns().header().toArray();

$(headers).on('click', function () {
    // do something
});
like image 70
蘇超人 Avatar answered Sep 29 '22 07:09

蘇超人