I need to set up sorting of multiple columns in an account transaction table. I decided to go with jQuery DataTables. Whenever I click on a column heading to sort that column (say column x), I want it to sort by column 3 for any matches in column x. If I click column 3, then it should sort by column 0 if there are matches in the column.
I saw fnSortListener and fnSort , and it looks like I could complete my task by attaching them to each column ... but this seems really redundant as each column has to do its secondary sorting in column 3, except for column 3.
So, is there a way to show DataTables to always do secondary sorting in column 3, and then specify an exception for column 3?
Any help is appreciated. I am very new to this plugin. Thank!
Edit
This is what I ended up with. The first 2D array indicates how to sort the first click, and the second 2d array indicates how to sort the second click.
var Sorter = function($dataTable) {
return {
bindMultiSort: function(headerSelector, firstOrderTuples, secondOrderTuples) {
var order = 0;
this.removeSorting(headerSelector).click(function() {
if (order === 0) {
$dataTable.fnSort(firstOrderTuples);
order = 1;
} else {
$dataTable.fnSort(secondOrderTuples);
order = 0;
}
});
},
removeSorting: function(headerSelector) {
var $header = $(headerSelector);
$header.unbind('click');
return $header;
}
};
};
function attachSecondarySorting($transactionsTable) {
var sorter = new Sorter($transactionsTable);
sorter.bindMultiSort('#posted', [[POSTED_DATE_COL, "asc"], [DESCRIPTION_COL, "asc"]], [[POSTED_DATE_COL, "desc"], [DESCRIPTION_COL, "asc"]]);
sorter.bindMultiSort('#received', [[RECEIVED_DATE_COL, 'asc'], [DESCRIPTION_COL, 'asc']], [[RECEIVED_DATE_COL, 'desc'], [DESCRIPTION_COL, 'asc']]);
sorter.bindMultiSort('#category', [[TRANSACTION_TYPE_COL, 'asc'], [POSTED_DATE_COL, 'desc'], [DESCRIPTION_COL, 'asc']], [[TRANSACTION_TYPE_COL, 'desc'],
sorter.bindMultiSort('#description', [[DESCRIPTION_COL, 'asc'], [POSTED_DATE_COL, 'desc']], [[DESCRIPTION_COL, 'desc'], [POSTED_DATE_COL, 'desc']]);
sorter.bindMultiSort('#moneyIn', [[MONEY_IN_COL, 'asc'], [DESCRIPTION_COL, 'asc']], [[MONEY_IN_COL, 'desc'], [DESCRIPTION_COL, 'asc']]);
sorter.bindMultiSort('#moneyOut', [[MONEY_OUT_COL, 'asc'], [DESCRIPTION_COL, 'asc']], [[MONEY_OUT_COL, 'desc'], [DESCRIPTION_COL, 'asc']]);
}