JavaScript: Tablesorter
Tablesorter is a jQuery plugin for turning a standard HTML table into a sortable table by adding sort to every column. You can customize the plugin to sort only some of the columns and specify the default sort.
On this page:
- Default Tablesort
- Customize the Tablesort
- More on Tables
Default Tablesort
Adding a class, tablesorter, to your table will give you basic table sorting functionality on all columns. Here’s a sortable table, with the tablesorter class applied.
Fruit | Color |
---|---|
Apple | Red |
Banana | Yellow |
Blueberry | Blue |
Grape | Purple |
Lime | Green |
Orange | Orange |
Default Tablesorter How-To
- Click the Drupal WebCMS editor Table button.
- In the table window, add headers, rows, and columns as needed. Click Ok.
- Disable rich-text, then add the tablesorter class to the table tag, <table class="tablesorter">. See below for some customization options.
Customize Tablesort
To further customize your tablesort, you can add additional JavaScript. Note that you must remove the class of tablesorter from your table in order to customize.
Set a Default Sorting Order
The default tablesorting option for tables will add sorting to every column by default. If you want certain columns to have a default sort, you can.
Assuming you have a table with four columns and an id of mytable, you can write JavaScript to sort the following way:
<script> $(document).ready(function() { $("#mytable").tablesorter({sortList: [ [ 3,1 ], [ 2,0 ] ] }); } ); </script>In the example above, I'm setting the fourth column to sort in descending order, and I'm setting the third column to sort in ascending order.
Column numbering starts with "0" for the first column. Play with the numbers to sort your preferred columns. The above snippet does not remove sorting from your other columns.
Remove Sorting for a Specific Column
Maybe you want a column to not be sortable (perhaps it's a column of descriptions). Here's how:
Assuming you have a table with four columns and an id of mytable, and you want the last column (the 4th, which is the 3rd when you start from 0), you can write JavaScript to set sorter: false:
<script> jQuery(document).ready(function() { jQuery("#mytable").tablesorter({ headers: { 3: {sorter: false} } }); }); </script>To Combine More than One Option
You can do multiple options at the same time. Here's code showing both of the above:
<script> jQuery(document).ready(function() { jQuery("#mytable").tablesorter({ sortList: [ [ 0,0 ], [ 1,0 ] ], headers: { 3: {sorter: false} } }); }); </script>