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.

foobar
Blythe50
Edmund104
Jonquil12
Lee55
Sky33
Archibald75
Emma70
Erin92
Edgar25

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.

download updated version

 
If you think this comment is spam or otherwise completely irrelevant here, feel free to hide it. The comment disappears immediately, though it is not deleted, so I have an option to "unhide" it later.
 

comment on this