SoluableNonagon SoluableNonagon - 1 year ago 99
Javascript Question

jQuery Datatables - how to programatically sort by a column

So I have a 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 Source

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

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

where 0 is the id of the column.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download