Search code examples
javascriptjquerytablesorter

How can I use tablesorter to sort multiple groups of rows separately?


I've seen similar questions about grouping rows in tablesorter but they are asking something slightly different than what I want. I would like a single table to have two groups of rows that get sorted separately. For example:

| col1 | col2 | col3  | <- this header never moves
|  A   |   1  |  1.5  |
|  J   |   3  |  2.7  | <- these three rows get sorted
|  X   |   2  |  1.2  |
|Totals|   6  |  5.4  | <- This totals the first group and never moves
| another header row  | <- this header never moves
|  B   |   5  |  5.0  |
|  L   |   3  |  8.2  | <- these three rows get sorted
|  N   |   7  |  3.3  |
|Totals|  15  | 16.5  | <- This totals the second group and never moves

This is sorted by col1. If I click on "col2", the top three rows should be A, X, J and the second three should be L, B, N. I'm sure this is possible but how can I get tablesorter to do it?


Solution

  • With my fork of tablesorter you can add multiple tbodies, and each will sort separately from the others. As for the total and extra header, also add these to separate tbody elements.

    <table class="tablesorter">
      <thead>
        <tr><th>col1</th><th>col2</th><th>col3</th></tr>
      </thead>
      <tbody><tr><!-- data --></tr></tbody>
      <tbody><tr><th>Totals</th><!-- ... --></tr></tbody>
      <tbody class="fake-header">
        <tr><th>col1</th><th>col2</th><th>col3</th></tr>
      </tbody>
      <tbody><tr><!-- more data --></tr></tbody>
      <tbody><tr><th>Totals</th><!-- ... --></tr></tbody>
    </table>
    

    No additional initialization is needed:

    $(function() {
      $('table').tablesorter({
        theme: 'blue',
        widgets: ['zebra']
      });
    });
    

    I set up this demo which includes the math widget to calculate the row totals automatically for you. The only changes needed are in the total row:

    <tbody>
      <tr>
        <th>Totals</th>
        <th data-math="above-sum"></th>
        <th data-math="above-sum"></th>
      </tr>
    </tbody>
    

    And include the widget, and output mask in the initialization:

    $(function() {
      $('table').tablesorter({
        theme: 'blue',
        widgets: ['zebra', 'math'],
        widgetOptions: {
          math_mask: '#,###.#'
        }
      });
    });