3

I am using the below jQuery to sort(descending) table on page load. It is working only after I click the arrows for descending or ascending.But,my requirement was to sort the table descending on page load.Any help is appreciated.

$(document).ready(function() { 
oTable = $('#personsList').dataTable({
                    "bJQueryUI": true,
                    "sPaginationType": "full_numbers",
                    "iDisplayLength": 25,
                    "aLengthMenu": [25, 50, 100, 150],
                    "aaSorting": [],                    
                    "bPaginate": false              
                });
1078081
  • 141
  • 2
  • 4
  • 11

4 Answers4

7

You should use that aaSorting parameter to initialize sorting on a specific column.

Below code sorts 1st column asc.

           $(document).ready(function() { 
                 oTable = $('#personsList').dataTable({
                "bJQueryUI": true,
                "sPaginationType": "full_numbers",
                "iDisplayLength": 25,
                "aLengthMenu": [25, 50, 100, 150],
                "aaSorting": [[0,'asc']],      //Sorts 1st column asc              
                "bPaginate": false              
            });

Complete datatables params reference

Selvakumar Arumugam
  • 79,297
  • 15
  • 120
  • 134
2

By this code you can sort individual columns on datatables by adding class 'sort-desc' or 'sort-asc' for sorting ascending and descending on page load

    $('.dom-table').each(function(index) {
        var sort_column=$('.dom-table thead tr').children().index('.sort-desc');
        var sort_oper='desc';
        if(sort_column < 0)
        {
            var sort_column=$('.dom-table thead tr').children().index('.sort-asc');
            sort_oper='asc';
            if(sort_column < 0)
            {
                sort_column=0;
            }
        }
        $(this).dataTable({
        "sDom": 'T<"clear">lfrtip',
        "aaSorting": [[sort_column,sort_oper]],
    });
});

I have not tested this code but it should work.

Taryn
  • 242,637
  • 56
  • 362
  • 405
md.fani
  • 41
  • 3
2

You can use order property to achieve the same.

For example in the following Table it will be sorted in descending order by 4th Column (index starts from ZERO!)

var table = $('#example').DataTable({

            "order": [
                      [3, 'desc']      
                     ]
        });

Checkout this Fiddle

vibs2006
  • 6,028
  • 3
  • 40
  • 40
0

What method is being called, when you click the sorting-arrows? Why don't you call just this method as the last method-call in the document.ready function?

devsnd
  • 7,382
  • 3
  • 42
  • 50