I have a table of names and ages that I want the user to be able to sort. When the page loads from the beginning, it sortListdisplays the lines in order from oldest to youngest, and then secondarily from A to Z.
I want the same thing (SECONDARY alphabetical sort) when the user clicks on the age <th>but sortForcemakes the primary alphabetical sort. Is there an alternative?
$('#super_results table').tablesorter({
sortForce: [[0,0]],
sortList: [[1,1],[0,0]]
});
Or am I misunderstanding sortForce? The documentation is here.
Update: I could not find a plugin to do this for me, so I wrote code that sorts a multidimensional array that builds a table. If you have an array with a name tableContentsthat tableContents[0]is a subarray of names and tableContents[1]a subarray of ages, then the call tableContents.sort(numSort)will sort the array first from the oldest to the youngest, and then from A to Z. ( num2SortSorts from the youngest to the oldest in the first place.) Then you can recreate the table with 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;
}
source
share