waffl waffl - 1 month ago 14
HTML Question

jQuery Tablesorter - Possible to group 'sorted' rows?

I am using jQuery tablesorter to sort a table and would like to produce some kind of separation between the groups of rows once they are sorted. For example, if I were using a table with Title, Category and Year, once sorted, all rows of a certain year would have an amount of padding between the others.

eg:

Title Cat 2012
Title Cat 2012
Title Cat 2012


Title Cat 2011
Title Cat 2011
Title Cat 2011


Title Cat 2010
Title Cat 2010


I imagine it would have to do with building a widget and comparing each row's value, and if a row does not match the previous value, then it should apply some padding of some sort but I am at a bit of a loss.

JSBIN:
http://jsbin.com/osehoy

Any direction/help would be greatly appreciated, thank you!

Answer

I wasn't sure if you wanted to just add an empty row in between or just make the row taller, so I opted for the latter. Here is the widget I made and a demo:

$.tablesorter.addWidget({
    id: 'spacer',
    format: function(table) {
        var c = table.config,
        $t = $(table),
        $r = $t.find('tbody').find('tr'),
        i, l, last, col, rows, spacers = [];
        if (c.sortList && c.sortList[0]) {
            $t.find('tr.spacer').removeClass('spacer');
            col = c.sortList[0][0]; // first sorted column
            rows = table.config.cache.normalized;
            last = rows[0][col]; // text from first row
            l = rows.length;
            for (i=0; i < l; i++) {
                // if text from row doesn't match last row,
                // save it to add a spacer
                if (rows[i][col] !== last) {
                    spacers.push(i-1);
                    last = rows[i][col];
                }
            }
            // add spacer class to the appropriate rows
            for (i=0; i<spacers.length; i++){
                $r.eq(spacers[i]).addClass('spacer');
            }
        }
    }
});

$('table').tablesorter({
    widgets : ['spacer']
});​

Update: My fork of tablesorter can sort across multiple tbodies, so the above script doesn't work without a slight modification rows = table.config.cache[0].normalized; - here is an updated demo that works with my fork. The above code will work with the original tablesorter plugin.

Comments