I am using DataTables to display some data and it works great but I want to customize it slightly and not sure how.
What I want to do is when a user clicks on a column heading to sort that column I want it to initially order descendingly rather than ascendingly. Is there any way to do this?
Using the order initialisation parameter, you can set the table to display the data in exactly the order that you want. 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.
FixedColumns provides the option to freeze one or more columns to the left or right of a horizontally scrolling DataTable. This allows information in the fixed columns to remain visible even when scrolling through the data set. This can be particularly useful if you wish to show a large number of columns.
DataTables saves the state of a table (its paging position, ordering state etc). When the stateSave option is enabled, it can be restored when the user reloads a page, or comes back to the page after visiting a sub-page.
Have a look at this: DataTables sorting direction control example
You can do something like:
$(document).ready(function() {
$('#example').dataTable( {
"aoColumns": [
{ "asSorting": [ "desc", "asc" ] }, //first sort desc, then asc
]
} );
} );
The current version of DataTables (1.10) provides the following way of switching this default sorting order with the property orderSequence
under columnDefs
(or columns
but less flexible).
Here's the documentation on orderSequence
.
"columnDefs": [
{ "orderSequence": [ "desc", "asc"], "targets": [ 1 ] },
]
As it also mentions, you may force a column to only sort when clicked as DESC or ASC which your interface may very well benefit from.
In my case, I needed to have columns descending their sort on initial click for an indeterminate number of columns so I decided to switch the example to target a column header's class
name rather than explicitly defining each column as "targets":[1],"targets":[2],...[n]
or programatically building an array of the indices of columns I cared about.
You can target columns multiple ways according to here.
The end result is a table definition like so:
<table><thead><tr>
<th class='descendFirst'>DESCend when first clicked</th>
<th>a normally sorted ASC->DESC->... column</th>
...
</tr></thead></table>
And Data Table empowered as such:
$("#table").dataTable({
"columnDefs": [
{"orderSequence": ["desc","asc"], "targets":"descendFirst" },
]
});
Voila! First click descending sort on all columns with a <th>
marked with a class of 'descendFirst' (an arbitrarily chosen, descriptive class name).
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