jQuery DataTables: How to Sort by a Specific Column on Load CodeUnit 04 APR 2010

I somehow missed this breezing through the available documentation on the DataTables website, but basically the question arose on how to force a table that has just been loaded (with Datatables applied naturally) to be sorted in a particular manner by default?

Well it turns out that the answer to this question is pretty simple indeed.

When constructing your dataTable object you can pass it an initializer parameter named aaSorting which essentially allows you to set which columns to sort on and also which direction to sort in.

Take a look at this sample dataTables initialization below:

$('#example').dataTable( {
		"bProcessing": true,
		"bServerSide": true,
		"iDisplayLength": 150,
		"bLengthChange": false,
		"sAjaxSource": "reservations_list.php",
		"aaSorting": [[ 5, "desc" ]]
	} );

If you look at the last parameter being fed to the constructor you’ll spot our aforementioned aaSorting being sneaked in there with an array value that is setting column six to be ordered in a descending fashion.

(You’ll note I say column six because obviously this is array based manipulation and as we all know, javascript utilizes zero-indexed arrays.)

And that is pretty much it. aaSorting allows us to set the default sorting pattern for any dataTables object.

Nice.

Related Posts:

About Craig Lotter

Software developer, husband and dad to two little girls. Writer behind An Exploring South African. I don't have time for myself any more.