ubertinador ubertinador - 1 year ago 64
jQuery Question

tablesorter custom display group header

First, I am using TableSorter 2.11.1 and jquery 1.9.1.

i used this demo to group my rows (http://mottie.github.io/tablesorter/docs/example-widget-grouping.html)
I sort my table by the date and i am grouping it by week like this image

enter image description here

What i want is to add the total of the price of the week in the grouping bar. like the number of rows in the week.

I search in the widget-grouping.js and i find the code to count the number of rows in the week

$tr = c.$table.find('tr.group-header').bind('selectstart', false);
if (wo.group_count) {
$(this).find('.group-count').html( wo.group_count.replace(/\{num\}/g, $(this).nextUntil('tr.group-header').filter(':visible').length) );

I am not a expert in jquery so i can't find a way to get the price and add it to the group header.


Actually your question made me realize that the grouping widget lacked this functionality. So, I added two new options in version 2.12.0 (new grouping widget demo):

  • group_callback - function which allows you to modify the group header text
  • group_complete - event name triggered on the table after the grouping widget has completed.

So now you can do something like this (demo):

var total = 0,
    targetColumn = 1,
    $table = $('table');

$table.on('groupingComplete', function(){
    // don't include the group header rows
    $table.find('tbody tr:not(.group-header)').each(function(){
        total += parseFloat( $(this).find('td').eq(targetColumn).text() );
    $table.find('.group-header .total').html( total );

    theme: 'blue',
    widthFixed: true,
    widgets: ['group'],
    widgetOptions: {
        // text added to the group header - {num} is the number of rows in that group
        group_count: ' ({num})',

        // add a group subtotal to the "Numeric" column
        group_callback: function ($cell, $rows, column, table) {
            // callback allowing modification of the group header labels
            // $cell = current table cell (containing group header cells '.group-name' & '.group-count'
            // $rows = all of the table rows for the current group; table = current table (DOM)
            // column = current column being sorted/grouped
            if (column === targetColumn) {
                var t, subtotal = 0;
                $rows.each(function () {
                    subtotal += parseInt($(this).find('td').eq(column).text());
                t = '; <span class="subtotal">' + subtotal + 
                    '</span>/<span class="total"></span>';


If you need to target more than one column, you can change targetColumn into an array, then use targetColumn.indexOf(column) >= 0 instead of column === targetColumn.