Kevin
Kevin

Reputation: 195

Sorting a table with jQuery TableSorter by multiple columns

I have a table that is currently being sorted with this code:

$(document).ready(function () {
    $(".statisticstable").tablesorter({
        sortList: [
            [5, 0]
        ],
        textExtraction: function (node) {
            if ($(node).hasClass('data')) {
                return $(node).attr('value');
            } else {
                return $(node).html();
            }
        }
    });
});

This currently sorts the table by the 5th column, however I am trying to add in a "favorite row" feature where it forces rows that have been "favored" to be pushed to the top, followed by the rest of the sorted list.

Is there anyway to do this?

Upvotes: 1

Views: 2231

Answers (1)

Mottie
Mottie

Reputation: 86403

I think what you want is the same as the answer for this StackOverflow question... basically, the user checks a box within the row and it gets moved into a separate tbody.

<table id="fav" class="tablesorter">
  <thead>
    <!-- make checkbox column unsortable "sorter-false" -->
    <th class="sorter-false"></th>
    <!-- etc -->
  </thead>

  <!-- add an "info" only (non-sorting) tbody -->
  <tbody class="tablesorter-infoOnly"></tbody>

  <tbody class="all">
    <tr>
      <td><input type="checkbox" /></td>
      <!-- etc -->
    </tr>
    <!-- etc -->
  </tbody>
</table>

If you want the rows within the "favorite" tbody to sort, then remove the tablesorter-infoOnly class.

Here is the code & demo for completeness

$(function() {

  var $table = $("#fav");
  $table.tablesorter({ sortList: [[0,0], [1,0]] });

  $table.on('click','input:checkbox', function() {
    var $this = $(this);
    if ($this.is(':checked')) {
      $this.closest('tr').prependTo("#fav tbody.tablesorter-infoOnly");
    } else {
      $this.closest('tr').appendTo("#fav tbody.all");
    }
    $this.trigger('update');
  });
});

Upvotes: 2

Related Questions