8

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

2
  • No. First hit in google... And what is the "header name"? Is it the text() content, is it a name="name" attribute or something else...? You could simply map your header names into integer constants, and use those constants instead of indexes. But what should be the benefit of doing that? A column index is basically just another name for the column anyway. 1 is the unique name for the second column... Commented Apr 17, 2017 at 4:12
  • 3
    There is always a tweak, like this -> jsfiddle.net/257jmovv but still cannot see the purpose, and it would only work more or less hardcoded on DOM tables anyway. Commented Apr 17, 2017 at 10:58

3 Answers 3

6

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

Sign up to request clarification or add additional context in comments.

Comments

6

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

Comments

1

I found a solution to fix this problem

var column1 = table.parents('table').find("th:contains('Your th text')")[0].cellIndex; 
var column2 = table.parents('table').find("th:contains('Your th text')")[0].cellIndex;
table.parents('table').dataTable({
  order: [[column1, 'asc'], [column2, 'asc']]
});

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.