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.

You might also enjoy:

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.
This entry was posted in Technology & Code, Tutorials and tagged , , , , , . Bookmark the permalink.
  • 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?

blog comments powered by Disqus