Easy table sorting with jQuery

Last modified date

Comments: 3

I came across a jQuery plug-in the other day to sort tables, and it works great and is exceptionally simple to implement (and as anyone who’s flicked through this blog knows, I like the simple things in life… Don’t need any more gray hairs popping up, you know!).

The plug-in is called tablesorter (found at tablesorter.com), by Christian Bach.

As I mentioned, it’s really simple to implement:

[code lang=”javascript”]
$("table.sortable").tablesorter();
[/code]

But also gives you the ability to add extra functionality by the use of ‘widgets’. One example of a widget from the tablesorter site is to add headers every number of rows. Here’s my rather paltry contribution to the widgets – highlighting rows when you hover over them.

[code lang=”javascript”]
$.tablesorter.addWidget({
id: "highlightOnHover",
format: function(table) {
$("tbody tr.highlight", table).remove();
$("tbody tr", table).hover(
function(){ $(this).children("td").addClass("highlight"); },
function(){ $(this).children("td").removeClass("highlight"); }
);
}
});
[/code]

Share

3 Responses

  1. Hi Andy,

    This is a bit off topic but I have not heard from you in a long time and I was wondering what was up. I noticed all the topics on your PHP forum are locked and the talker site seems to be down (always just says “It works!” or some such).

    I was not sure what the best way to contact you was.

    Cheers,
    Uzume

  2. I am using this sorting library too. Have you run into an issue with sorting percents?

    Given the following values { 2.0%, 25%, 10% }, the library will sort the values as {10%, 2.0%, 25% } because of the plain text sorting on the 1 versus the 2 (in both 2.0 and 25).

  3. bnaffas; have you tried creating your own parser for the column that contains the percentages? Something like:

    [code language=”javascript”]
    $.tablesorter.addParser({
    id : ‘percentages’,
    type : ‘numeric’,
    is : function(s) { return false; },
    format : function(s) {
    var reg = /(.*?)%/i;
    if (reg.test(s)) {
    var match = reg.exec(s);
    return parseInt(match[1]);
    } else {
    return parseInt(s);
    }
    }
    });
    [/code]

    And than you include it such as:

    [code language=”javascript”]
    $("table").tablesorter({
    headers: {
    3: { sorter:’percentages’ }
    }
    });
    [/code]

    where ‘3’ is the column number where your percentages are.

    As I’ve just got it together this morning, I can’t promise the above is exact! 🙂

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.