Search code examples
tablesorter

Tablesorter custom equations on calculated data


I need to sum two columns, then find the difference between those two. The use case is simple: in one column I have all the purchases and the second one contains all the transactions, the user will see the difference.

Here is the relevant code for the calculation:

<tfoot>
<tr>
<th>Total</th>
<th data-math="col-sum"></th>
<th data-math="col-sum"></th>
<th data-math="row-difference"></th>
</tr>
</tfoot>

And the formula can be something really simple like

$.tablesorter.equations['difference'] = function(arry) {
    return arry[1] - arry[2];
  };

How would you make it work?


Solution

  • The way the math widget is set up, it prioritizes rows calculations before column calculations. So in this case, the footer row will try to calculate the row difference before calculating the column sum.

    To fix this, change the math_priority widget option so that the 'col' comes before 'row' (demo):

    $(function() {
      $.tablesorter.equations.difference = function(arry) {
        return arry[1] - arry[2];
      };
      $("table").tablesorter({
        theme: 'blue',
        widgets: ['math', 'zebra'],
        widgetOptions: {
          // default [ 'row', 'above', 'below', 'col' ]
          // move 'col' first in this case
          math_priority: ['col', 'row', 'above', 'below']
        }
      });
    });