Phil
Phil

Reputation: 4069

Dynamic Sorting using custom table tags DataTables jQuery

Using the excellent dataTables jQuery plugin, I'm having trouble creating a dynamic array for the "aaSorting" parameter. As per the docs, the "aaSorting" parameter takes an array (or array of arrays) containing the column and the sort order. I need to create a dynamic array for the tables I'm working on, and use the values of the custom table attributes of sortCol and sortOrder which I've added for the tables aaSorting param. I thought I could do this...

var sortCol = $('#mytable').attr('sortCol');
var sortOrder = $('#mytable').attr('sortOrder');
var sortData = [];
if(sortCol != '' && sortOrder != ''){
     sortData[sortCol] = sortOrder;
}

Then in my dataTable initialization, use the sortData var as the value for the "aaSorting" parameter. However, this does not work. Can anyone provide any insight as to how the array must be constructed in order for dataTables to use it for sorting.

var myTableObject = dataTable({
     "oLanguage": "Search",
     "aaSorting": sortData
});

Upvotes: 0

Views: 4997

Answers (2)

Primoshenko
Primoshenko

Reputation: 140

There is a way to dynamically update the sorting of a Datatable after it has been created and defined using jQuery:

Using the fnSort() method:

// Sort the first column ascending
$('#myTable').DataTable().fnSort([0, 'asc']);

// Sort the second column descending
$('#myTable').DataTable().fnSort([1, 'desc']);

// Sort multiple columns
$('#myTable').DataTable().fnSort([[0, 'asc'], [2, 'desc']]);

Upvotes: 0

Binary Alchemist
Binary Alchemist

Reputation: 1620

aaSorting is an array of arrays. Each nested array has two elements. The first is the column number, and the second is the order (i.e. asc or desc). You are using a one dimensional array for aaSorting, try [[0, "asc"]]

Updated

var sortCol = $('#mytable').attr('sortCol');
var sortOrder = $('#mytable').attr('sortOrder');
var sortData = [];
if(sortCol != '' && sortOrder != ''){
     sortData.push( [sortCol, sortOrder] );
}

Example

// Sort by 3rd column first, and then 4th column
$(document).ready( function() {
  $('#example').dataTable( {
    "aaSorting": [[2,'asc'], [3,'desc']]
  } );
} );

Upvotes: 3

Related Questions