6

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() );
 } );
1
  • what version of datatables? Commented Dec 25, 2014 at 20:20

6 Answers 6

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

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

$(headers).on('click', function () {
    // do something
});
Sign up to request clarification or add additional context in comments.

1 Comment

You if you want to get column name then you can try this. var headers = table.columns().header().toArray(); $(headers).on('click', function (e) { // do something console.log("column Name", e.target.innerHTML); });
2

You get the index when clicking on headers like this :

$('#example thead').on('click', 'th', function () {
  var index = table.column(this).index();
  alert('index : '+index);
});

This works with hidden columns, reordered columns ans so on as well.

fiddle -> http://jsfiddle.net/1kjooq9w/

1 Comment

My problem was the way I selected my table. See my answer stackoverflow.com/a/27650447/1537365
1

http://jsfiddle.net/zwkggt7r/3/

Try it

$(document).ready(function() {
    var table = $('#example').dataTable();
    table.on('click', 'th', function() {
        var info = table.fnSettings().aaSorting;
        var idx = info[0][0];
        alert(idx);
    });
});

1 Comment

Doesn't work with the latest version of DataTables (Error: table.fnSettings is not a function)..
1

The code snippet I had found was correct except for one small piece.

By using the below code it correctly create the dataTable.

var table = $('#example').dataTable( {
    "data": data_set,
    "columns": column_titles,
    "columnDefs": column_defs
} );

But it does not correctly select the table. So later when I try to access the table object it does not have the method "cell".

Code should be corrected as

var table = $('#example').DataTable( {...

So now the table has the "cell" method.

So the final code will be as below.

var table = $('#example').DataTable( {
    "data": data_set,
    "columns": column_titles,
    "columnDefs": column_defs
} );

$("#example").find("thead").on('click', 'th', function(){
    var col_idx =  table.column(this).index();
    console.log("colId = " + col_idx);
});

2 Comments

Yes, correct when you click on <td>'s , eg on data - but it fails when you click on the headers.
attention: if dataTable with scrollY, it will create a separate table for header, original thead will hidden
0

It's been a long while since I used DataTables, but I think you can achieve it with cell().index(). Check out the doc: https://datatables.net/reference/api/cell().index()

$('#example thead').on('click', 'th', function () {         
    alert( 'Column clicked on: ' + table.cell(this).index().column);
});

2 Comments

I get an error "Uncaught TypeError: undefined is not a function" when I try this
My problem was the way I selected my table. See my answer stackoverflow.com/a/27650447/1537365
0

You can easily do that using order method of the table. My technique works well.

We need to do two things here.

  • Get current column index
  • Apply ascending or descending action on particular column on click of a icon

Here let us assume we have a button or link to which click to bind.

$(".arrow-sort-ascending").bind("click", {
 // Sorting should happen here
}

Getting column index

I use generic way to get column name. If you are using Jquery, we can fetch the column index using this.

myColumn = $(parent).prevAll().length

where parent should be the th of particular column.

Applying ascending or descending sort

 // ascending
 myTable.order([myColumn, "asc"]).draw()

So if we put the code in a single section, it looks like this.

table = myTable // This is datatable you initialized

$(".arrow-sort-ascending").bind("click", {table: table}, function(event){
    parent = $(event.target).parent()
    myIndex = $(parent).prevAll().length;
    table.order([myIndex, "asc"]).draw()
}

So whenever we click the arrrow-up icon, it sorts the clicked column.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.