TableSort: custom sort rules
05 April 2008 // javascript. things.
Meritxell asked me how to use TableSort to sort a column based on a DOM attribute (checkbox "checked" value in that case). Well, in the original version it wasn't possible, but it was very easy to add.
Check some checkboxes and click 'foo' to sort this table.
| foo | bar |
| Blythe | 50 |
| Edmund | 104 |
| Jonquil | 12 |
| Lee | 55 |
| Sky | 33 |
| Archibald | 75 |
| Emma | 70 |
| Erin | 92 |
| Edgar | 25 |
The first column uses the following custom comparison function
// sort by checkboxes and then alphabetically
function compareCheckboxes(textA, textB, tdA, tdB) {
var t = Number(tdA.firstChild.checked) -
Number(tdB.firstChild.checked);
if(t != 0) return t;
return TableSort.compare.alpha(textB, textA);
}
When TS compares two cells, it calls the function with four arguments. The first two are text content from the first and from the second table cell. The next two (that's what I added) are cells "themselves", i.e. DOM <TD> elements, so that you can access cells' DOM contents in the function.
Of course, the above comparison needs to be enabled, you have to add something like this to the onload sequence:
TableSort.enable('tableID', 'columnTitle', compareCheckboxes);
See TableSort docs for more details.
comment on this