jQuery DataTables: How to Sort by a Specific Column on Load

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:

  • DataTables is a fantastic plug-in for the jQuery Javascript library that I use for pretty much all my web development projects. It is a highly flexible tool, based upon the foundations of progressive enhancement, which will add advanced interaction controls to any HTML table – in other words, it creates useful dyna ...

  • I’ve mentioned the wonderful jQuery plugin DataTables a number of times before, the awesome little trick that instantly transforms any HTML table fed to it into a fully sortable, paginated, searchable and zebra-striped table, requiring the most minimum of coding to implement. Today's tip looks at how you can spe ...

  • DataTables is a fantastic jQuery-powered plugin that supercharges your ordinary HTML tables and as such is pretty much my de facto method for presenting tabular data. I often include special 'action' columns in my table where I lump in all my row data manipulating buttons and thus don't particularly want to allo ...

  • I really do love the awesome DataTable plugin which creates useful dynamic, with oodles of extra functionality, tables out of plain old vanilla HTML tables. Today's quick tip however looks at how one destroys an already instantiated DataTable instance, say because you want to recreate it at a later stage in a compl ...

  • As it has quickly become apparent on this site, my two current favourites in the land of web development is the fantastic jQuery javascript library and the brilliant jQuery-based DataTables plugin that gives you instant dynamic table features applied to any bog standard HTML table. The problem that I'm solving tod ...

About Craig Lotter

Craig Lotter is an established web developer and application programmer, with strong creative urges (which keep bursting out at the most inopportune moments) and a seemingly insatiable need to love all things animated. Living in the beautiful coastal town of Gordon's Bay in South Africa, he games, develops, takes in animated fare, trains under the Funakoshi karate style and for the most part, simply enjoys life with his amazing wife and daughter. Oh, and he draws ever now and then too.

  • Mitchell

    How do you sort more than one field?

  • Mitchell

    How do you sort more than one field?

  • http://www.craiglotter.co.za Craig Lotter

    @Mitchell – Off the top of my head, I’m not actually sure if there is a native way of doing that without running datatables through a dynamic load script and messing with the SQL there. Perhaps the best place would be to ask on the main datatables.net forum itself?

  • http://www.craiglotter.co.za Craig Lotter

    @Mitchell – Off the top of my head, I’m not actually sure if there is a native way of doing that without running datatables through a dynamic load script and messing with the SQL there. Perhaps the best place would be to ask on the main datatables.net forum itself?

  • Guest

    html 5!!! amazing

  • Ken Elliott

    Mitchel sorting more than one field is easy. “aaSorting”:[[0,"asc"],[3,"desc"]].  I stumbled on this post when I was looking for a way to set a default sort column on a per table basis, without having to write custom js for each table. I couldn’t find anything pleasing, so I wrote one. Hopefully people will find it and they won’t use the others that I found :)

    http://devken.com/blog/sort-the-jquery-datatables-dynamically-on-load

  • j_blotus

    worked for me! thanks

  • Lukas McLean

    Hi there,

    I’ve used the sorting feature many times now with joy about its easyness … however i’ve come across the situation where i do not want to resort the original dataset on page load at all. However, simply removing the “aaSorting” option does not block the resorting like expected, but just sorts the first column alphabetically.

    How can I disable the rearrangement of the dataset?

    • Lukas McLean

      Allright, found a solution on stackoverflow: http://stackoverflow.com/questions/4964388/is-there-a-way-to-disable-initial-sorting-for-jquery-datables

      just pass an empty array 

      “aaSorting”: [],

      to override any default sortings.

      Oh and by the way: you might wanna take a look of the sorting of these blog posts. seems like you got a desc string sort here that mixes up the actual ages like:2 years ago2 hours ago
      1 month ago

      cheers!

  • Nhatphutho

    thanks for your help

  • vaibhav shukla

    This didn’t work for me.
    I am populating the datatable with an ajax call populating aaData. Theres a fifth column of Date, and i want a default sorted order to be in descending order of date i.e. most recent first.
    This is what is inside my ajax call
    $.ajax( { type : “GET”, url : “ajaxBacklog”, contentType : ‘application/json’, data : null, dataType : ‘json’, success : function(json) { oTable = $(“#backlogTable”).dataTable({ “aaData” : json.aaData, “bProcessing” : true, “sPaginationType” : “full_numbers”, “bJQueryUI” : true, “bRetrieve” : true, “bPaginate” : true, “bSort” : true, “aaSorting” : [[ 4, "desc" ]] “oLanguage”: { “sEmptyTable”: “No records found.” }, “aoColumns”: [ { "bSortable": true, sClass: "alignCenter"}, { sClass: "left"}, { sClass: "left"}, { sClass: "left"}, { sClass: "left"}, { sClass: "left"}, { sClass: "left"}, ], “error”: function() { alert(“Failed to load Data”); } }); }
    } );

    It din’t turned out the way you’ve explained. Please tell where m i going wrong. By default the backlogs are coming is ascending order of the date.

    • j0rdax

      try single quotes for desc and remember the comma between options: “aaSorting” : [[ 4, 'desc' ]], also make sure that the column you want to sort on has bSortable set to true

  • j0rdax

    @google-907f2df06f0662d5cd7a0c7713e286a1:disqus, try single quotes for desc and remember the comma between options: “aaSorting” : [[ 4, 'desc' ]], also make sure that the column you want to sort on has bSortable set to true

  • http://www.felipevallades.com.br/ Felipe

    Thanks a lot!!!!