Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery Datatables - how to programatically sort by a column

So I have a datatable:

$(tables[i]).DataTable({
    paging: false,
    searching: false,
    info: false,
    ordering: true,
    autoWidth: false,
    columns: [ ... column stuff here ... 
        {name: "Name"},
        {name: "Account"},
        {name: "Number"}
    ]
});

later in code, I watch for a click event on a button so that I can grab some data from the table and then sort by a column

var columnName = $('.mySelectBox').val();
var columnNumber = 0;

if(columnName === "Account")
    columnNumber = 1;

var table = $(tables[i]).DataTable();

I would like to now sort by either column 0 or column one on this button click. But not on any other column.

//this doesn't work for me
table.sort( [ [columnNumber, 'desc'] ] );
like image 831
SoluableNonagon Avatar asked Jul 16 '15 16:07

SoluableNonagon


People also ask

How do I sort a specific column in a DataTable?

The existing answers are using legacy DataTables syntax. Versions 1.10+ should use the following syntax: $('table'). dataTable({ "pageLength": -1, //display all records "order": [[ 0, "desc" ]] // Sort by first column descending });

How do I sort DataTables in multiple columns?

As you would expect with a desktop application, DataTables allows you to sort by multiple columns at the same time. This multiple sorting mechanism is always active if the bSort initialiser is true (it is by default) and the end user can activate it by 'shift' clicking on the column they want to add to the sort.

How do you sort DataTables with date in descending order?

date format should be YYYY-MM-DD. sort it *"order": [[ 3, "desc" ]] * and hide the td, th display none.


1 Answers

I use .order() instead of .sort(). Example:

$('#dataTables-example').DataTable().order([0, 'desc']).draw();

where 0 is the id of the column.

like image 140
muchwow Avatar answered Oct 01 '22 15:10

muchwow