12

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?

1

3 Answers 3

25

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'] ] );
} );
Sign up to request clarification or add additional context in comments.

1 Comment

I want to sort the table on 2 column not on 0 or 1
7

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)."

1 Comment

oTable.fnSort() was giving an error. But your solution works. Thanks!
2

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.