I have a table of names and ages that I want the user to be able to sort. When the page initally loads, sortList
lists the rows in order from oldest to youngest, and then secondarily from A to Z.
I want the same thing (a SECONDARY alphabetical sort) when the user actually clicks on the age <th>
, but sortForce
is making the alphabetical sort primary. Is there an alternative?
$('#super_results table').tablesorter({
sortForce: [[0,0]],
sortList: [[1,1],[0,0]]
});
Or am I misunderstanding sortForce
? Documentation here.
Update: I couldn't find a plugin to do this for me, so I wrote some code that sorts the multidimensional array that builds the table. If you have an array called tableContents
, and tableContents[0]
is a subarray of names and tableContents[1]
is a subarray of ages, then calling tableContents.sort(numSort)
will sort the array first from oldest to youngest, and then from A to Z. (num2Sort
sorts youngest to oldest first.) Then you can recreate the table using createHtml(data)
, and use the result to replace the old table.
function numSort(a, b) {
if (a[1] === b[1]) {
if (a[0] === b[0]) {
return 0;
}
return (a[0] < b[0]) ? -1 : 1;
}
return (a[1] < b[1]) ? 1 : -1;
}
function num2Sort(a, b) {
if (a[1] === b[1]) {
if (a[0] === b[0]) {
return 0;
}
return (a[0] < b[0]) ? -1 : 1;
}
return (a[1] < b[1]) ? -1 : 1;
}
function createHtml(data) {
var completeListLength = MYAPP.completeList.length,
html = '<table>';
html += '<thead>';
html += '<tr>';
html += '<th>names</th>';
html += '<th>ages</th>';
html += '</tr>';
html += '</thead>';
html += '<tbody>';
for (var i = 0; i < completeListLength; i += 1) {
html += '<tr>';
html += '<td>' + data[i][0] + '</td>';
html += '<td>' + data[i][1] + '</td>';
html += '</tr>';
}
html += '</tbody>';
html += '</table>';
return html;
}
I was having the same problem, and stumbled upon this: