Versions 1.10+ should use the following syntax: $('table'). dataTable({ "pageLength": -1, //display all records "order": [[ 0, "desc" ]] // Sort by first column descending });
The order parameter is an array of arrays where the first value of the inner array is the column to order on, and the second is 'asc' (ascending ordering) or 'desc' (descending ordering) as required. order is a 2D array to allow multi-column ordering to be defined.
Sorting by a click on the header. When you click on the header, DataTable starts to display a special control indicating which column the table is currently sorted by and the direction of this sorting (ascending or descending). Each new click on the same header will reverse the sorting direction.
There are a couple of options:
Just after initialising DataTables, remove the sorting classes on the TD element in the TBODY.
Disable the sorting classes using http://datatables.net/ref#bSortClasses . Problem with this is that it will disable the sort classes for user sort requests - which might or might not be what you want.
Have your server output the table in your required sort order, and don't apply a default sort on the table (aaSorting:[]
).
Here is the actual code that does it...
$(document).ready(function()
{
var oTable = $('#myTable').dataTable();
// Sort immediately with column 2 (at position 1 in the array (base 0). More could be sorted with additional array elements
oTable.fnSort( [ [1,'asc'] ] );
// And to sort another column descending (at position 2 in the array (base 0).
oTable.fnSort( [ [2,'desc'] ] );
} );
To not have the column highlighted, modify the CSS like so:
table.dataTable tr.odd td.sorting_1 { background-color: transparent; }
table.dataTable tr.even td.sorting_1 { background-color: transparent; }
You can use the fnSort function, see the details here:
http://datatables.net/api#fnSort
Best option is to disable sorting and just feed data with desired sort order (from database or other source). Try to add this to your 'datatable': "bSort": false
Datatables supports HTML5 data-* attributes for this functionality.
It supports multiple columns in the sort order (it's 0-based)
<table data-order="[[ 1, 'desc' ], [2, 'asc' ]]">
<thead>
<tr>
<td>First</td>
<td>Another column</td>
<td>A third</td>
</tr>
</thead>
<tbody>
<tr>
<td>z</td>
<td>1</td>
<td>$%^&*</td>
</tr>
<tr>
<td>y</td>
<td>2</td>
<td>*$%^&</td>
</tr>
</tbody>
</table>
Now my jQuery is simply $('table').DataTables();
and I get my second and third columns sorted in desc / asc order.
Here's some other nice attributes for the <table>
that I find myself reusing:
data-page-length="-1"
will set the page length to All (pass 25 for page length 25)...
data-fixed-header="true"
... Make a guess
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With