I am working on datatable plugin in Jquery. And have to set the default column by which the data is sorted so I mean that :
I have a table with 4 columns and by default the data is sorted by column no 1, I want that the data should be sorted by column number 2 or 3.
How that can be done:
$('#tblMainTable').dataTable({
"bJQueryUI" : true,
"sDom" : 'R<"H"lfr>t<"F"ip<',
"aoColumns" : [
{"bSortable" : false},
null,
null,
null,
{"bSortable" : false},
{"bSortable" : false}
],
"aaSorting": [[ 2, "desc" ]]
});
I specified that in "aaSorting" but not getting the result.
Please shed some light?
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.
$('table'). dataTable({ "pageLength": -1, //display all records "order": [[ 0, "desc" ]] // Sort by first column descending }); Reference: Sorting.
Sorting in DataTables is based on the detected type of the data column (you can add your own type detection functions, or override automatic detection using sType). With this specific type given to the column, DataTables will apply the required sorting function.
Use columnDefs option to remove sorting from a column. Pass column index in targets within [] (Indexing starting from 0) and set orderable to false .
The example in the datatable api does it like this:
$(document).ready(function() {
var oTable = $('#example').dataTable();
// Sort immediately with columns 0 and 1
oTable.fnSort( [ [0,'asc'], [1,'asc'] ] );
} );
I know you have the answer now, but here is an even more easier way from the DatatTable API
$('#tblMainTable').dataTable({
"order": [[1, "desc"], [2, "desc"]]
});
Do note that the index is from 0 'Zero' so the example means "Column 2 and 3 is the default sorting column and its Descending (use asc for Ascending)."
I know you got the answer, but just for record
You can also sort it from server side by using the parameter
params.iSortCol_0
it is basically an integer 0,1,2.. means first,second,third.. column. so you can write a switch before fetching the data..
String sortOn = 'firstcolumnname'; //default
switch(params.iSortCol_0 as int) {
case 0:
sortOn = 'id';
break;
......
}
and include this in order by of your query
order by ${sortOn}
Hope this will help
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