SoluableNonagon SoluableNonagon - 4 months ago 18
Javascript Question

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'] ] );

Answer

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

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

where 0 is the id of the column.

Comments