Author: Christian Bach
Version: 2.1+ (forked from version 2.0.5, changelog)
Licence: Dual licensed under MIT or GPL licenses.

Contents

  1. Introduction
  2. Demo
  3. Getting started
  4. Examples
  5. Configuration
  6. Widget Options (New v2.1)
  7. Methods
  8. Events
  9. Download
  10. Compatibility
  11. Support
  12. Credits

Introduction

tablesorter is a jQuery plugin for turning a standard HTML table with THEAD and TBODY tags into a sortable table without page refreshes. tablesorter can successfully parse and sort many types of data including linked data in a cell. It has many useful features including:

Demo

Account # First Name Last Name Age Total Discount Difference Date
A42b Peter Parker 28 $9.99 20.9% +12.1 Jul 6, 2006 8:14 AM
A255 John Hood 33 $19.99 25% +12 Dec 10, 2002 5:14 AM
A33 Clark Kent 18 $15.89 44% -26 Jan 12, 2003 11:14 AM
A1 Bruce Almighty 45 $153.19 44.7% +77 Jan 18, 2001 9:12 AM
A102 Bruce Evans 22 $13.19 11% -100.9 Jan 18, 2007 9:12 AM
A42a Bruce Evans 22 $13.19 11% 0 Jan 18, 2007 9:12 AM

TIP! Sort multiple columns simultaneously by holding down the shift key and clicking a second, third or even fourth column header!

Getting started

To use the tablesorter plugin, include the jQuery library and the tablesorter plugin inside the <head> tag of your HTML document:

<script type="text/javascript" src="/path/to/jquery-latest.js"></script>
<script type="text/javascript" src="/path/to/jquery.tablesorter.js"></script>

tablesorter works on standard HTML tables. You must include THEAD and TBODY tags:

<table id="myTable" class="tablesorter">
  <thead>
    <tr>
      <th>Last Name</th>
      <th>First Name</th>
      <th>Email</th>
      <th>Due</th>
      <th>Web Site</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>Smith</td>
      <td>John</td>
      <td>[email protected]</td>
      <td>$50.00</td>
      <td>http://www.jsmith.com</td>
    </tr>
    <tr>
      <td>Bach</td>
      <td>Frank</td>
      <td>[email protected]</td>
      <td>$50.00</td>
      <td>http://www.frank.com</td>
    </tr>
    <tr>
      <td>Doe</td>
      <td>Jason</td>
      <td>[email protected]</td>
      <td>$100.00</td>
      <td>http://www.jdoe.com</td>
    </tr>
    <tr>
      <td>Conway</td>
      <td>Tim</td>
      <td>[email protected]</td>
      <td>$50.00</td>
      <td>http://www.timconway.com</td>
    </tr>
  </tbody>
</table>

Start by telling tablesorter to sort your table when the document is loaded:

$(function(){
  $("#myTable").tablesorter();
});

Click on the headers and you'll see that your table is now sortable! You can also pass in configuration options when you initialize the table. This tells tablesorter to sort on the first and second column in ascending order.

$(function(){
  $("#myTable").tablesorter({ sortList: [[0,0], [1,0]] });
});

NOTE! tablesorter will auto-detect most data types including numbers, dates, ip-adresses for more information see Examples

Examples

These examples will show what's possible with tablesorter. You need Javascript enabled to run these samples, just like you and your users will need Javascript enabled to use tablesorter.

Basic

Sorting

Parsers / Extracting Content

Widgets / Plugins

Advanced

Adding / Removing Content

Change Header Style


Other

Options & Events

Playgrounds & Other demos

Metadata - setting inline options


Configuration

tablesorter has many options you can pass in at initialization to achieve different effects
TIP! Click on the link in the property column to reveal full details (or toggle|show|hide all) or double click to update the browser location.

Property Type Default Description Link
Property Type Default Description Link
cancelSelection Boolean true Indicates if tablesorter should disable selection of text in the table header (TH). Makes header behave more like a button.
cssAsc String "tablesorter-headerSortUp" The CSS style used to style the header when sorting ascending. Example from the blue skin:
th.tablesorter-headerSortUp {
  background-color: #8dbdd8;
  background-image: url(black-asc.gif);
}
cssChildRow String "expand-child" Add this css class to a child row that should always be attached to its parent. Click on the "cssChildRow" link to toggle the view on the attached child row. Ex:1 2
This is an entirely new row, but attached to the row above while sorting
cssChildRow Example HTML:
<table width="100%" border="1">
  <thead>
    <tr>
      <th>Item #</th>
      <th>Name</th>
      <th>Available</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>12345</td>
      <td>Toy Car</td>
      <td>5</td>
    </tr>
    <tr class="expand-child"> <!-- this row will remain attached to the above row, and not sort separately -->
      <td colspan="3">
        It's a toy car!
      </td>
    </tr>
    <tr>
      <td>23456</td>
      <td>Toy Plane</td>
      <td>2</td>
    </tr>
    <tr class="expand-child"> <!-- this row will remain attached to the above row, and not sort separately -->
      <td colspan="3">
        It's a toy plane!
      </td>
    </tr>
    <tr class="expand-child"> <!-- this row will remain attached to the above two rows, and not sort separately -->
      <td colspan="3">
        and it flies!
      </td>
    </tr>
  </tbody>
</table>
					
cssDesc String "tablesorter-headerSortDown" The CSS style used to style the header when sorting descending. Example from the blue skin:
th.tablesorter-headerSortDown {
  background-color: #8dbdd8;
  background-image: url(black-desc.gif);
}
cssHeader String "tablesorter-header" The CSS style used to style the header in its unsorted state. Example from the blue skin:
th.tablesorter-header {
  background-color: #e6eeee;
  background-image: url(black-bg.gif);
  background-repeat: no-repeat;
  background-position: center right;
  border-collapse: collapse;
  cursor: pointer;
  font-size: 12px;
  padding: 4px 20px 4px 4px;
}
cssInfoBlock String "tablesorter-infoOnly" All tbodies with this class name will not have its contents sorted. New! v2.2.

With the addition of multiple tbody sorting in v2.2, you can now insert a non-sorting tbody within the table by adding this class to the tbody.
<tbody class="tablesorter-infoOnly">
  <tr>
    <th>The contents of this tbody</th>
  </tr>
  <tr>
    <td>will not be sorted</td>
  </tr>
</tbody>
As an example, I've split up this options table into three (3) tbodies. The first contains the active options, the second is the info block with a row that only contains the text "Deprecated Options", and the last tbody contains the deprecated options. Sort the table to see how each tbody sorts separately.

NOTE! The pager plugin will only be applied to the first tbody, as always. I may work on modifying this behavior in the future, if I can figure out the best implementation.

selectorRemove String "tr.remove-me" This CSS class name can be applied to all rows that are to be removed prior to triggering a table update. (New v2.1).

It was necessary to add this option because some widgets add table rows for styling (see the writing custom widgets demo) and if a table update is triggered ($('table').trigger('update');) those added rows will automatically become incorporated into the table.
dateFormat String "mmddyyyy" Set the date format. Here are the available options. (Modified v2.0.23).
  • "mmddyyyy" (default)
  • "ddmmyyyy"
  • "yyyymmdd"
In previous versions, this option was set as "us", "uk" or "dd/mm/yy". This option was modified to better fit needed date formats. It will only work with four digit years!

The sorter should be set to "shortDate" and the date format can be set in the "dateFormat" option or set for a specific columns within the "headers" option. See the demo page to see it working.
$(function(){
  $("table").tablesorter({

    dateFormat : "mmddyyyy", // default date format

    // or to change the format for specific columns,
    // add the dateFormat to the headers option:
    headers: {
      0: { sorter: "shortDate" }, // "shortDate" with the default dateFormat above
      1: { sorter: "shortDate", dateFormat: "ddmmyyyy" }, // day first format
      2: { sorter: "shortDate", dateFormat: "yyyymmdd" }  // year first format
    }

  });
});
Individual columns can be modified by adding the following, set in order of priority Modified! v2.3.1:
  • jQuery data data-dateFormat="mmddyyyy".
  • metadata class="{ dateFormat: 'mmddyyyy'}". This requires the metadata plugin.
  • headers option headers : { 0 : { dateFormat : 'mmddyyyy' } }.
  • header class name class="dateFormat-mmddyyyy".
  • Overall dateFormat option.
Example
debug Boolean false Boolean flag indicating if tablesorter should display debuging information useful for development. Example
delayInit Boolean false Setting this option to true will delay parsing of all table cell data until the user initializes a sort. This speeds up the initialization process of very large tables, but the data still needs to be parsed, so the delay is still present upon initial sort. Example
emptyTo String "bottom" Boolean flag indicating how tablesorter should deal with empty table cells. (Modified v2.1.16).
  • bottom - sort empty table cells to the bottom.
  • top - sort empty table cells to the top.
  • none or zero - sort empty table cells as if the cell has the value equal to zero.
Individual columns can be modified by adding the following, set in order of priority:
  • jQuery data data-empty="top".
  • metadata class="{ empty: 'top'}". This requires the metadata plugin.
  • headers option headers : { 0 : { empty : 'top' } }.
  • header class name class="empty-top".
  • Overall emptyTo option.
emptyToBottom option was added in v2.1.11, then replaced by the emptyTo option in v2.1.16.
Example
headerList Array [ ] (empty array) Internal list of each header element as selected using jQuery selectors in the selectorHeaders option. Not really useful for normal usage.
headers Object null An object of instructions for per-column controls in the format: headers: { 0: { option: setting }, ... }

For example, to disable sorting on the first two columns of a table: headers: { 0: { sorter: false}, 1: {sorter: false} }.

The plugin attempts to detect the type of data that is contained in a column, but if it can't figure it out then it defaults to alphanumeric. You can easily override this by setting the header argument (or column parser). See the full list of default parsers here or write your own.
$(function(){
  $("table").tablesorter({
    headers: {

      // See example - Disable first column
      0: { sorter: false },

      // See example 2: Sort column numerically & treat any text as if its value is:
      1: { sorter: "digit", empty: "top" },  // zero; sort empty cells to the top
      2: { sorter: "digit", string: "max" }, // maximum positive value
      3: { sorter: "digit", string: "min" }, // maximum negative value

      // Sort the fifth column by date & set the format
      4: { sorter: "shortDate", dateFormat: "yyyymmdd" }  // year first format

      // See example 3: lock the sort order
      // this option will not work if added as metadata
      5: { lockedOrder: "asc" },

      // See Example 4: Initial sort order direction of seventh column
      6: { sortInitialOrder: "desc" },

      // Set the filter to false to disable the filter widget in this column
      // See the "Applying the filter widget" demo
      7: { filter: false }

    }
  });
});
Ex:1 2 3 4
ignoreCase Boolean true When true, text sorting will ignore the character case. If false, upper case characters will sort before lower case. New! v2.2.
initWidgets Boolean true Apply widgets after table initializes New! v2.3.5.
When true, all widgets set by the widgets option will apply after tablesorter has initialized, this is the normal behavior.

If false, the each widget set by the widgets option will be initialized, meaning the "init" function is run, but the format function will not be run. This is useful when running the pager plugin after the table is set up. The pager plugin will initialize, then apply all set widgets.

Why you ask? Well, lets say you have a table with 1000 rows that will have the pager plugin applied to it. Before this option, the table would finish its setup, all widgets would be applied to the 1000 rows, pager plugin initializes and reapplies the widgets on the say 20 rows showing; making the widget application to 100 rows unnecessary and a waste of time. So, when this option is false, widgets will only be applied to the table after the pager is set up.
onRenderHeader Function null This function is called when classes are added to the TH tags. You can use this to modify the HTML in each header tag for additional styling.

In versions 2.0.6+, all TH text is wrapped in a span by default. In the example below, the header cell (TH) span is given a class name (source).
$(function(){
  $("table").tablesorter({
    onRenderHeader: function (){
      $(this).find('div').addClass('roundedCorners');
    }
  });
});
and you'll end up with this HTML (only the thead is shown)
<thead>
  <tr>
    <th class="header"><span class="roundedCorners">Column 1</span></th>
    <th class="header"><span class="roundedCorners">Column 2</span></th>
  </tr>
</thead>
Example
parsers Object { } Internal list of all of the parsers. Here is a complete list of default parsers:

sorter: falsedisable sort for this column.
sorter: "text"Sort alpha-numerically.
sorter: "digit"Sort numerically.
sorter: "currency"Sort by currency value (supports "£$€¤¥¢").
sorter: "ipAddress"Sort by IP Address.
sorter: "url"Sort by url.
sorter: "isoDate"Sort by ISO date (YYYY-MM-DD or YYYY/MM/DD).
sorter: "percent"Sort by percent.
sorter: "usLongDate"Sort by date (U.S. Standard, e.g. Jan 18, 2001 9:12 AM).
sorter: "shortDate"Sort by a shorten date (see dateFormat).
sorter: "time"Sort by time (23:59 or 12:59 pm).
sorter: "metadata"Sort by the sorter value in the metadata - requires the metadata plugin.

Check out the headers option to see how to use these parsers in your table (example #1).
Or add a header class name using "sorter-" plus the parser name (example #2), this includes custom parsers (example #3).
Ex:1 2 3
selectorHeaders String "> thead th" jQuery selectors used to find the header cells.
You can change this, but the table will still need the required thead and tbody before this plugin will work properly.
Added > to the selector in version 2.3 to prevent targetting nested table headers. Modified! v2.3
sortForce Array null Use to add an additional forced sort that is prepended to sortList.

For example, sortForce: [[0,0]] will sort the first column in ascending order. After the forced sort, the user selected column(s), or during initialzation, the sorting order defined in the sortList will follow. And lastly, the sort defined in the sortAppend option will be applied. More explicitly:

There are three options to determine the sort order and this is the order of priority:
  1. sortForce forces the user to have this/these column(s) sorted first (null by default).
  2. SortList is the initial sort order of the columns.
  3. SortAppend is the default sort that is added to the end of the users sort selection (null by default).
The value of these sort options is an array of arrays and can include one or more columns. The format is an array of instructions for per-column sorting and direction in the format: [[columnIndex, sortDirection], ... ] where columnIndex is a zero-based index for your columns left-to-right and sortDirection is 0 for Ascending and 1 for Descending. A valid argument that sorts ascending first by column 1 and then column 2 looks like: [[0,0],[1,0]].
$(function(){
  $("table").tablesorter({
    sortForce  : [[0,0]],        // Always sort first column first
    sortList   : [[1,0], [2,0]], // initial sort columns (2nd and 3rd)
    sortAppend : [[3,0]]         // Always add this sort on the end (4th column)
  });
});
Example
sortList Array null Use to add an initial sort to the table.

The value contains an array of instructions for per-column sorting and direction in the format: [[columnIndex, sortDirection], ... ] where columnIndex is a zero-based index for your columns left-to-right and sortDirection is 0 for Ascending and 1 for Descending. A valid argument that sorts ascending first by column 1 and then column 2 looks like: [[0,0],[1,0]]. Please see sortForce for more details on other sort order options.

This option can also be set using jQuery data (New! v2.3.1) or metadata on the table:
jQuery data<table data-sortlist="[[0,0],[4,0]]">
Meta data<table class="tablesorter {sortlist: [[0,0],[4,0]]}">
Example
sortAppend Array null Use to add an additional forced sort that will be appended to the dynamic selections by the user.

For example, can be used to sort people alphabetically after some other user-selected sort that results in rows with the same value like dates or money due. It can help prevent data from appearing as though it has a random secondary sort.

The value contains an array of instructions for per-column sorting and direction in the format: [[columnIndex, sortDirection], ... ] where columnIndex is a zero-based index for your columns left-to-right and sortDirection is 0 for Ascending and 1 for Descending. A valid argument that sorts ascending first by column 1 and then column 2 looks like: [[0,0],[1,0]]. Please see sortForce for more details on other sort order options.
Example
sortInitialOrder String "asc" The direction a column sorts when clicking the header for the first time. Valid arguments are "asc" for Ascending or "desc" for Descending.

This order can also be set by desired column using the headers option (Added in v2.0.8).

Individual columns can be modified by adding the following, set in order of priority Modified! v2.3.1:
  • jQuery data data-sortInitialOrder="asc".
  • metadata class="{ sortInitialOrder: 'asc'}". This requires the metadata plugin.
  • headers option headers : { 0 : { sortInitialOrder : 'asc' } }.
  • header class name class="sortInitialOrder-asc".
  • Overall sortInitialOrder option.
Ex:1 2
sortLocaleCompare Boolean false Boolean flag indicating if certain accented characters within the table will be replaced with their equivalent characters. Modified! v2.2.
  • This option no longer switches the sort to use the String.localeCompare method.
  • When this option is true, the text parsed from table cells will convert accented characters to their equivalent to allow the alphanumeric sort to properly sort.
  • If false (default), any accented characters are treated as their value in the standard unicode order.
  • The following characters are replaced for both upper and lower case (information obtained from sugar.js sorting equivalents table):
    • áàâãä replaced with a
    • ç replaced with c
    • éèêë replaced with e
    • íìİîï replaced with i
    • óòôõö replaced with o
    • úùûü replaced with u
    • ß replaced with S
  • Please see the example page for instrcutions on how to modify the above equivalency table.
  • If you would like to continuing using the String.localeCompare method, then set the sortLocaleCompare option to false and use the new textSorter option as follows:
    $('table').tablesorter({
      textSorter: function(a,b) {
        return a.localeCompare(b);
      }
    });

NOTE: See the Language wiki page for language specific examples and how to extend the character equivalent tables seen in the sortLocaleCompare demo.

Boolean flag indicating whenever to use javascript String.localeCompare method or not.
This is only used when comparing text with international character strings. A sort using localeCompare will sort accented characters the same as their unaccented counterparts.
Example
sortReset Boolean false Setting this option to true will allow you to click on the table header a third time to reset the sort direction. (New v2.0.27). Example
sortRestart Boolean false Setting this option to true will start the sort with the sortInitialOrder when clicking on a previously unsorted column. (New v2.0.31). Example
sortMultiSortKey String "shiftKey" The key used to select more than one column for multi-column sorting. Defaults to the shift key. The other options are "ctrlKey" or "altKey". Reference: https://developer.mozilla.org/en/DOM/MouseEvent Example
stringTo String "max" Boolean flag indicating how tablesorter should deal with text inside of numerically sorted columns. (New v2.1.16).

String options was initially set in the header options only. Overall option added and values changed in version 2.1.16; setting the value to:
  • "max" will treat any text in that column as a value greater than the max (more positive) value. Renamed from "max+".
  • "min" will treat any text in that column as a value greater than the min (more negative) value. Renamed from "max-".
  • "top" will always sort the text to the top of the column.
  • "bottom" will always sort the text to the bottom of the column.
  • "none" or "zero" will treat the text as if it has a value of zero.
Individual columns can be modified by adding the following, set in order of priority:
  • jQuery data data-string="top".
  • metadata class="{ string: 'top'}". This requires the metadata plugin.
  • headers option headers : { 0 : { string : 'top' } }.
  • header class name class="string-top".
  • Overall stringTo option.
Example
tableClass String "tablesorter" This class was required in the default markup in version 2.0.5. But in version 2.0.6, it was added as an option.

Change this option if you are not using the default css, or if you are using a completely custom stylesheet.
textExtraction String Or Function "simple" Defines which method is used to extract data from a table cell for sorting. The built-in option is "simple" which is the equivalent of doing this inside of the textExtraction function: $(node).text();.

You can customize the text extraction by writing your own text extraction function "myTextExtraction" which you define like:
var myTextExtraction = function(node, table, cellIndex){
  // extract data from markup and return it
  // originally: return node.childNodes[0].childNodes[0].innerHTML;
  return $(node).find('selector').text();
}
$(function(){
  $("#myTable").tableSorter( { textExtraction: myTextExtraction } );
});
tablesorter will pass the current table cell object for you to parse and return. Thanks to Josh Nathanson for the examples. Updated to a jQuery example by Rob G (Mottie).

Now if the text you are finding in the script above is say a number, then just include the headers sorter option to specify how to sort it. Also in this example, we will specify that the special textExtraction code is only needed for the second column ("1" because we are using a zero-based index). All other columns will ignore this textExtraction function.

Added table and cellIndex variables to the textExtraction function in version 2.1.2.

$(function(){
  $("table").tablesorter({
    textExtraction: {
      1: function(node, table, cellIndex) {
           return $(node).find("span:last").text();
      }
    },
    headers: {
      1: { sorter : "digit" }
    }
  });
});
Example
textSorter Function null Replace the default sorting algorithm with a custom one using this option.

Include a script like naturalSort.js as follows:
$(function(){
  $("table").tablesorter({
    textSorter : naturalSort
  });
});
or use the localeCompare sort
$(function(){
  $("table").tablesorter({
    textSorter: function(a,b) {
      return a.localeCompare(b);
    }
  });
});
There's no need to worry about reverse sorting, it's taken care of by the plugin.
Example
usNumberFormat Boolean true Indicates how tablesorter should deal with a numerical format: (New v2.1.3).
true U.S. 1,234,567.89
false German:
French:
1.234.567,89
1 234 567,89
Example
widgets Array [ ] (empty array) Initialize widgets using this option ( e.g. widgets : ['zebra'], or custom widgets widgets: ['zebra', 'myCustomWidget'];, see this demo on how to write your own custom widget ). Example
widthFixed Boolean false Indicates if tablesorter should apply fixed widths to the table columns. This is useful for the Pager companion.
Requires the jQuery dimension plugin to work. This is now part of the jQuery core.
Example
widgetOptions Object { } As of version 2.1, all widget options have been moved into this option. This is a move to store all widget specific options in one place so as not to polute the main table options. All current widgets have been modified to use this new option. (New v2.1).

Previously documented widget options widgetZebra, widgetColumns and widgetUitheme will be retained for backwards compatibility.

Use the widgetOptions option as follows, please note that each option is followed by a comma (except the last one):
$(function(){
  $("table").tablesorter({

    // initialize a bunch of widgets
    widgets: ["zebra", "uitheme", "columns", "filter", "stickyHeaders"],

    widgetOptions: {

      // zebra widget: adding zebra striping, using content and default styles - the ui css removes the background
      // from default even and odd class names included for this demo to allow switching themes
      // [ "even", "odd" ]
      zebra   : ["ui-widget-content even", "ui-state-default odd"],

      // uitheme widget: change default uitheme icons
      // find the full list of icons here: http://jqueryui.com/themeroller/ (hover over them for their name)
      // default icons: ["ui-icon-arrowthick-2-n-s", "ui-icon-arrowthick-1-s", "ui-icon-arrowthick-1-n"]
      // ["up/down arrow (cssHeaders/unsorted)","down arrow (cssDesc/descending)","up arrow (cssAsc/ascending)"]
      uitheme : ["ui-icon-carat-2-n-s", "ui-icon-carat-1-s", "ui-icon-carat-1-n"],

      // columns widget: change the default column class names
      // primary is the first column sorted, secondary is the second, etc
      columns : [ "primary", "secondary", "tertiary" ],

      // filter widget: If there are child rows in the table (rows with class name from "cssChildRow" option)
      // and this option is true and a match is found anywhere in the child row, then it will make that row
      // visible; default is false
      filter_childRows : false,

      // filter widget: css class applied to the table row containing the filters & the inputs within that row
      filter_cssFilter : "tablesorter-filter",

      // filter widget: Set this option to true to use the filter to find text from the start of the column
      // So typing in "a" will find "albert" but not "frank", both have a's; default is false
      filter_startsWith : false,

      // stickyHeaders widget: css class name applied to the sticky header
      stickyHeaders    : "tablesorter-stickyHeader"

    }

  });
});
Example
Deprecated Options
widgetColumns Object with Array { css:[ "primary", "secondary", "tertiary" ] } This option is being deprecated! It has been replaced by widgetOptions.columns; but is still available for backwards compatibility.

When the column styling widget is initialized, it automatically applied the default class names of "primary" for the primary sort, "secondary" for the next sort, "tertiary" for the next sort, and so on (add more as needed)... (New v2.0.17). Use the widgetColumns option to change the css class name as follows:
$(function(){
  $("table").tablesorter({
    widgets: ["columns"], // initialize column styling of the table
    widgetColumns: { css: ["primary", "secondary", "tertiary" ] }
  });
});
widgetUitheme Object with Array { css: [ "ui-icon-arrowthick-2-n-s", "ui-icon-arrowthick-1-s", "ui-icon-arrowthick-1-n" ] } This option is being deprecated! It has been replaced by widgetOptions.uitheme; but is still available for backwards compatibility.

Used when the ui theme styling widget is initialized. It automatically applies the default class names of "ui-icon-arrowthick-2-n-s" for the unsorted column, "ui-icon-arrowthick-1-s" for the descending sort and "ui-icon-arrowthick-1-n" for the ascending sort. (New v2.0.9). Find more jQuery UI class names by hovering over the Framework icons on this page: http://jqueryui.com/themeroller/

Use the widgetUitheme option to change the css class name as follows:
$(function(){
  $("table").tablesorter({
    widgets: ["uitheme"], // initialize ui theme styling widget of the table
    widgetUitheme: {
      css: [
        "ui-icon-carat-2-n-s", // Unsorted icon
        "ui-icon-carat-1-s",   // Sort up (down arrow)
        "ui-icon-carat-1-n"    // Sort down (up arrow)
      ]
    }
  });
});
widgetZebra Object with Array { css: [ "even", "odd" ] } This option is being deprecated! It has been replaced by widgetOptions.zebra; but is still available for backwards compatibility.

When the zebra striping widget is initialized, it automatically applied the default class names of "even" and "odd". Use the widgetZebra option to change the css class name as follows:
$(function(){
  $("table").tablesorter({
    widgets: ["zebra"], // initialize zebra striping of the table
    widgetZebra: { css: [ "normal-row", "alt-row" ] }
  });
});

Widget Options

tablesorter widgets have many options, and to better organize them, they now are grouped together inside of the widgetOptions
TIP! Click on the link in the property column to reveal full details (or toggle|show|hide all) or double click to update the browser location.

Property Type Default Description Link
Property Type Default Description Link
columns Array [ "primary", "secondary", "tertiary" ] columns widget: When the column styling widget is initialized, it automatically applied the default class names of "primary" for the primary sort, "secondary" for the next sort, "tertiary" for the next sort, and so on (add more as needed)... (Modified v2.1).

Use the "columns" option to change the css class name as follows:
$(function(){
  $("table").tablesorter({
    widgets: ["columns"], // initialize column styling of the table
    widgetOptions : {
      columns: [ "primary", "secondary", "tertiary" ]
    }
  });
});
Example
filter_childRows Boolean false Filter widget: If there are child rows in the table (rows with class name from "cssChildRow" option) and this option is true and a match is found anywhere in the child row, then it will make that row visible. (Modified v2.1).

Use the filter_childRows option include child row text as follows:
$(function(){
  $("table").tablesorter({
    widgets: ["filter"],
    widgetOptions : {
      filter_childRows : true
    }
  });
});
filter_cssFilter String 'tablesorter-filter' Filter widget: This is the class name applied to the filter header row (tr) and each input within that row. If you change it from the default class name of "tablesorter-filter" make sure you also update the css! (New v2.1).

Use the "tablesorter-filter" option to change the css class name as follows:
$(function(){
  $("table").tablesorter({
    widgets: ["filter"],
    widgetOptions : {
      // css class applied to the table row containing the filters & the inputs within that row
      filter_cssFilter : "tablesorter-filter"
    }
  });
});
Example
filter_startsWith Boolean false Set this option to true to use the filter to find text from the start of the column, so typing in "a" will find "albert" but not "frank", both have a's. (New v2.1).

Use the filter_startsWith option as follows:
$(function(){
  $("table").tablesorter({
    widgets: ["filter"],
    widgetOptions : {
      filter_startsWith : true
    }
  });
});
Example
filter_ignoreCase Boolean true Set this option to false to make the column content search case-insensitive, so typing in "a" will not find "Albert". New! v2.3.4

Use the filter_ignorecase option as follows:
$(function(){
  $("table").tablesorter({
    widgets: ["filter"],
    widgetOptions : {
      filter_ignoreCase : false
    }
  });
});
Example
filter_functions Object null Customize the filter widget by adding a select dropdown with content, custom options or custom filter functions. New! v2.3.6

Use the "filter_functions" option in three different ways:
  • Make a select dropdown list of all column contents. Repeated content will be combined.
    $(function(){
      $("table").tablesorter({
        widgets: ["filter"],
        widgetOptions: {
          filter_functions: {
            // Add select menu to this column
            // set the column value to true, and/or add "filter-select" class name to header
            0 : true
          }
        }
      });
    });
    Alternately, instead of setting the column filter funtion to true, give the column header a class name of "filter-select". See the demo.

  • Make a select dropdown list with custom option settings. Each option must have a corresponding function which returns a boolean value; return true if there is a match, or false with no match.

    Regex example

    $(function(){
      $("table").tablesorter({
        widgets: ["filter"],
        widgetOptions: {
          // function variables:
          // e = exact text from cell
          // n = normalized value returned by the column parser
          // f = search filter input value
          // i = column index
          filter_functions: {
            // Add these options to the select dropdown (regex example)
            2 : {
              "A - D" : function(e, n, f, i) { return /^[A-D]/.test(e); },
              "E - H" : function(e, n, f, i) { return /^[E-H]/.test(e); },
              "I - L" : function(e, n, f, i) { return /^[I-L]/.test(e); },
              "M - P" : function(e, n, f, i) { return /^[M-P]/.test(e); },
              "Q - T" : function(e, n, f, i) { return /^[Q-T]/.test(e); },
              "U - X" : function(e, n, f, i) { return /^[U-X]/.test(e); },
              "Y - Z" : function(e, n, f, i) { return /^[Y-Z]/.test(e); }
            }
          }
        }
      });
    });

    Comparison example

    $(function(){
      $("table").tablesorter({
        widgets: ["filter"],
        widgetOptions: {
          // function variables:
          // e = exact text from cell
          // n = normalized value returned by the column parser
          // f = search filter input value
          // i = column index
          filter_functions: {
            // Add these options to the select dropdown (numerical comparison example)
            // Note that only the normalized (n) value will contain numerical data
            // If you use the exact text, you'll need to parse it (parseFloat or parseInt)
            4 : {
              "< $10"      : function(e, n, f, i) { return n < 10; },
              "$10 - $100" : function(e, n, f, i) { return n >= 10 && n <=100; },
              "> $100"     : function(e, n, f, i) { return n > 100; }
            }
          }
        }
      });
    });
    Note: if the filter_ignoreCase option is true, it DOES alter the normalized value (n) by making it all lower case.

  • Make a custom filter for the column.
    $(function(){
      $("table").tablesorter({
        widgets: ["filter"],
        widgetOptions: {
          // function variables:
          // e = exact text from cell
          // n = normalized value returned by the column parser
          // f = search filter input value
          // i = column index
          filter_functions: {
            // Exact match only
            1 : function(e, n, f, i) {
              return e === f;
            }
          }
        }
      });
    });
    Note: if the filter_ignoreCase option is true, it DOES alter the normalized value (n) by making it all lower case.

Example
filter_searchDelay Numeric 300 Set this option to the number of milliseconds to delay the search. New! v2.3.4

Use the filter_searchDelay option as follows:
$(function(){
  $("table").tablesorter({
    widgets: ["filter"],
    widgetOptions : {
      filter_searchDelay : 500
    }
  });
});
If you want to want to initialize the filter without user input, target any one of the filters and trigger a "search".
// target the first filter input
// this method will begin the search after the searchDelay time
$('input.tablesorter-filter:eq(0)').trigger('search');

// this method will begin the search immediately
$('input.tablesorter-filter:eq(0)').trigger('search', false);
stickyHeaders String 'tablesorter-stickyHeader' stickyHeaders widget: This is the class name applied to the sticky header row (tr). If you change it from the default class name of "tablesorter-stickyHeader" make sure you also update the css! (New v2.1).

Use the "stickyHeaders" option to change the css class name as follows:
$(function(){
  $("table").tablesorter({
    widgets: ["stickyHeaders"],
    widgetOptions : {
      // css class name applied to the sticky header
      stickyHeaders : "tablesorter-stickyHeader"
    }
  });
});
Example
uitheme Array [ "ui-icon-arrowthick-2-n-s", "ui-icon-arrowthick-1-s", "ui-icon-arrowthick-1-n" ] uitheme widget: This widget option replaces the previous widgetUitheme. It is used when the ui theme styling widget is initialized. It automatically applies the default class names of "ui-icon-arrowthick-2-n-s" for the unsorted column, "ui-icon-arrowthick-1-s" for the descending sort and "ui-icon-arrowthick-1-n" for the ascending sort. (Modified v2.1).

Find more jQuery UI class names by hovering over the Framework icons on this page: http://jqueryui.com/themeroller/

Use the "widgetUitheme" option to change the css class name as follows:
$(function(){
  $("table").tablesorter({
    widgets: ["uitheme"], // initialize ui theme styling widget of the table
    widgetOptions: {
      uitheme : [
        "ui-icon-carat-2-n-s", // Unsorted icon
        "ui-icon-carat-1-s",   // Sort up (down arrow)
        "ui-icon-carat-1-n"    // Sort down (up arrow)
      ]
    }
  });
});
Example
zebra Array [ "even", "odd" ] zebra widget: When the zebra striping widget is initialized, it automatically applied the default class names of "even" and "odd". (Modified v2.1).

Use the "zebra" option to change the css class name as follows:
$(function(){
  $("table").tablesorter({
    widgets: ["zebra"], // initialize zebra striping of the table
    widgetOptions: {
      zebra: [ "normal-row", "alt-row" ]
    }
  });
});
Example

Methods

tablesorter has some methods available to allow updating, resorting or applying widgets to a table after it has been initialized.
TIP! Click on the link in the method column to reveal full details (or toggle|show|hide all) or double click to update the browser location.

Method Description Link
addRows Use this method to add table rows. (New v2.0.16).
It does not work the same as "update" in that it only adds rows, it does not remove them.
Also, use this method to add table rows while using the pager plugin. If the "update" method is used, only the visible table rows continue to exist.
// Add multiple rows to the table
  var row = '<tr><td>Inigo</td><td>Montoya</td><td>34</td>' +
    '<td>$19.99</td><td>15%</td><td>Sep 25, 1987 12:00PM</td></tr>',
    $row = $(row),
    // resort table using the current sort; set to false to prevent resort, otherwise
    // any other value in resort will automatically trigger the table resort.
    // A callback method was added in 2.3.9.
    resort = true,
    callback = function(table){
      alert('rows have been added!');
    };
  $('table')
    .find('tbody').append($row)
    .trigger('addRows', [$row, resort, callback]);
Example
sorton Use this method to sort an initialized table in the desired order.
// Choose a new sort order
var sort = [[0,0],[2,0]],
    callback = function(table){
        alert('new sort applied to ' + table.id);
    };
// Note that the sort value below is inside of another array (inside another set of square brackets)
// A callback method was added in 2.3.9.
$("table").trigger("sorton", [sort, callback]);
Example
update Update the stored tablesorter data and the table.
// Add new content
$("table tbody").append(html);

// let the plugin know that we made a update
// the resort flag set to anything BUT false (no quotes) will trigger an automatic
// table resort using the current sort
// A callback method was added in 2.3.9.
var resort = true,
    callback = function(table){
        alert('new sort applied');
    };
$("table").trigger("update", [resort, callback]);

// As of version 2.0.14, the table will automatically resort (using the current sort selection)
// after the update, so include the following if you want to specify a different sort

// set sorting column and direction, this will sort on the first and third column
var sorting = [[2,1],[0,0]];
$("table").trigger("sorton", [sorting]);
Example
appendCache Update a table that has had its data dynamically changed; used in conjunction with "update".
Use this method when more than just one cell like in the "updateCell" method, but you may possibly have to trigger two events: both "update" and "appendCache".

Note: This is the only method the pager widget uses - the entire table is stored in the cache, but only the visible portion is actually exists in the table.
// Table data was just dynamically changed (more than one cell)
$("table")
  .trigger("update")
  .trigger("appendCache");
updateCell Update a table cell in the tablesorter data.
$(function() {
  $("table").tablesorter();

  $("td.discount").click(function(){

    // randomize a number
    var resort = false,
        discount = '$' + Math.round(Math.random() * Math.random() * 100) + '.' +
     ('0' + Math.round(Math.random() * Math.random() * 100)).slice(-2);
    $(this).text(discount);

    // update the table, so the tablesorter plugin knows its value
    // set resort flag to false to prevent automatic resort (since we're using a different sort below)
    // leave the resort flag as undefined, or with any other value, to automatically resort the table
    // $("table").trigger("updateCell", [this]); < - resort is undefined so the table WILL resort
    $("table").trigger("updateCell", [this, resort]);

    // As of version 2.0.14, the table will automatically resort (using the current sort selection)
    // after the update, so include the following if you want to specify a different sort

    // set sorting column and direction, this will sort on the first and third column
    var sorting = [[3,1]];
    $("table").trigger("sorton", [sorting]);

    return false;
  });
});
Example
applyWidgetId Apply the selected widget to the table, but the widget will not continue to be applied after each sort. See the example, it's easier than describing it.
$(function(){
  // initialize tablesorter without the widget
  $("table").tablesorter();

  // click a button to apply the zebra striping
  $("button").click(function(){
    $('table').trigger('applyWidgetId', ['zebra']);
});
Example
applyWidgets Apply the set widgets to the table. This method can be used after a table has been initialized, but it won't work unless you update the configuration settings. See the example, it's easier than describing it.
// Update the list of widgets to apply to the table (add or remove)
  $("table").data("tablesorter").widgets = ["zebra"];

  // This method applies the widget - no need to keep updating
  $('table').trigger('applyWidgets');
}); 
Example
destroy Use this method to remove tablesorter from the table.
// Remove tablesorter and all classes
$("table").trigger("destroy");

// Remove tablesorter and all classes but the "tablesorter" class on the table
$("table").trigger("destroy", [false];

Events

tablesorter has some methods available to allow updating, resorting or applying widgets to a table after it has been initialized.
TIP! Click on the link in the event column to reveal full details (or toggle|show|hide all) or double click to update the browser location.

Event Description Link
initialized This event fires when tablesorter has completed initialization.
$(function(){

  // bind to initialized event BEFORE initializing tablesorter
  $("table")
    .bind("tablesorter-initialized",function(e, table) {
      // do something after tablesorter has initialized
    });

  // initialize the tablesorter plugin
  $("table").tablesorter({
    // this is equivalent to the above bind method
    initialized : function(table){
      // do something after tablesorter has initialized
    }
  });

});
sortBegin This event fires immediately before tablesorter begins resorting the table.
$(function(){

  // initialize the tablesorter plugin
  $("table").tablesorter();

  // bind to sort events
  $("table").bind("sortBegin",function(e, table) {
    // do something crazy!
  });
});
sortStart This event fires immediately after the tablesorter header has been clicked, initializing a resort.
$(function(){

  // initialize the tablesorter plugin
  $("table").tablesorter();

  // bind to sort events
  $("table")
    .bind("sortStart",function(e, table) {
      $("#overlay").show();
    })
    .bind("sortEnd",function(e, table) {
      $("#overlay").hide();
    });
});
Example
sortEnd This event fires when tablesorter has completed resorting the table.
$(function(){

  // initialize the tablesorter plugin
  $("table").tablesorter();

  // bind to sort events
  $("table")
    .bind("sortStart",function(e, table) {
      $("#overlay").show();
    })
    .bind("sortEnd",function(e, table) {
      $("#overlay").hide();
    });
});
Example
pagerChange This event fires when the pager plugin begins to render the table on the currently selected page. (New v2.0.7).
$(function(){

  // initialize the sorter
  $("table")
    .tablesorter()

    // initialize the pager plugin
    .tablesorterPager({
      container: $("#pager")
    })

    // bind to pager events
    .bind('pagerChange pagerComplete', function(e,c){
      // c.totalPages contains the total number of pages
      $('#display').html( e.type + " event triggered, now on page " + (c.page + 1) );
    });

});
Example
pagerComplete This event fires when the pager plugin has completed its render of the table on the currently selected page. (New v2.0.7).
$(function(){

  // initialize the sorter
  $("table")
    .tablesorter()

    // initialize the pager plugin
    .tablesorterPager({
      container: $("#pager")
    })

    // bind to pager events
    .bind('pagerChange pagerComplete', function(e,c){
      // c.totalPages contains the total number of pages
      $('#display').html( e.type + " event triggered, now on page " + (c.page + 1) );
    });

});
Example

Download

Full release - Plugin, Documentation, Add-ons, Themes. Download: zip or tar.gz

Pick n choose - Place at least the required files in a directory on your webserver that is accessible to a web browser. Record this location.

Required: Optional / Add-Ons: Themes:

Browser Compatibility

tablesorter has been tested successfully in the following browsers with Javascript enabled:

jQuery Browser Compatibility

Support

If you are having a problem with the plugin or you want to submit a feature request, please submit an issue.

If you would like to contribute, fork a copy on github.

Support is also available through the jQuery Mailing List or StackOverflow.

Access to the jQuery Mailing List is also available through Nabble Forums.

Credits

Written by Christian Bach.

Documentation written by Brian Ghidinelli, based on Mike Alsup's great documention.
Missing documentation, alphanumeric sort, numerous widgets and other changes added by Mottie.

John Resig for the fantastic jQuery