Select a column to sort in datatables

I am using a table plugin for jQuery (datatables) and want to specify a sorcerer for sorting.

table example:

Name | email | year

My table code:

$('#table_id').dataTable({
    "stateSave": true,
    "aoColumnDefs": [{
        'bSortable': false
    }],
    "oLanguage": {
        "oPaginate": {
            "sPrevious": "",
            "sNext": ""
        }
    },
    "iDisplayLength": 15,
    "aLengthMenu": [
        [15, 20, 25, -1],
        [15, 20, 25, "All"]
    ],
     "responsive": true

});

At the moment, it is sorted by customer name, yet my sql are sorted by year. How can I override this in datatable?

+4
source share
2 answers

I think this will help you.

$(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'] ] );
} );
+1
source

Decision

Use orderto set the initial order for the table.

$('#example').DataTable({
    "order": [ 1, 'asc' ]
});

where 1is the zero column index for sorting. Use ascto sort in ascending order and descto sort in descending order.

Demo

See this jsFiddle for code and demos.

+1
source

Source: https://habr.com/ru/post/1610400/


All Articles