Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery Datatable sort by column header

Basically, jQuery Datatable allow us to sort data by column index.

"order": [1, 'desc']

I wonder if we can sort by column header name? For example:

"order": ['my_column_name', 'desc']

Thankyou Alex

like image 830
AlexPham Avatar asked Apr 17 '17 02:04

AlexPham


2 Answers

Is there a way to use the name, data or class of the column in order to set the default column sort? No - not at this time.

Although this thread is posted in June-2015 but still I couldn't find such functionality in latest version of DataTable.

As a side note! You have to provide column index while ordering data of DataTable but you can get Column Name on which ordering is applied.

var order = table.order();
var columnIndex = order[0][0]; //column index
var orderDirection =order[0][1]; // asc or desc

//Get column header text;
var title = table.column(order[0][0]).header();
var columnName = $(title).html(); //Column Name

Demo

like image 60
mmushtaq Avatar answered Oct 16 '22 09:10

mmushtaq


First find the column index by jquery,

Then insert the column index in datatable function.

var sort_col = $('#table').find("th:contains('your column name')")[0].cellIndex;

$('#table').dataTable({             
    order: [[ sort_col, 'desc' ]]                
  });

This worked for me. Hope this helps. Thanks

like image 2
Shinto Joseph Avatar answered Oct 16 '22 07:10

Shinto Joseph