Author: Christian Bach
Version: 2.0.9 (changelog)
Licence: Dual licensed under MIT or GPL licenses.

Update! New version!, and the tablesorter docs are now available in russian, head over to tablesorter.ru

Helping out! If you like tablesorter and you're feeling generous, take a look at my Amazon Wish List or make a donation.

Comments and love letters can be sent to: .

Contents

  1. Introduction
  2. Demo
  3. Getting started
  4. Examples
  5. Configuration
  6. Methods New!
  7. Events New!
  8. Download
  9. Compatibility
  10. Support
  11. 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>jsmith@gmail.com</td>
      <td>$50.00</td>
      <td>http://www.jsmith.com</td>
    </tr>
    <tr>
      <td>Bach</td>
      <td>Frank</td>
      <td>fbach@yahoo.com</td>
      <td>$50.00</td>
      <td>http://www.frank.com</td>
    </tr>
    <tr>
      <td>Doe</td>
      <td>Jason</td>
      <td>jdoe@hotmail.com</td>
      <td>$100.00</td>
      <td>http://www.jdoe.com</td>
    </tr>
    <tr>
      <td>Conway</td>
      <td>Tim</td>
      <td>tconway@earthlink.net</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 Metadata - setting inline options Advanced Companion plugins

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)

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 "headerSortUp" The CSS style used to style the header when sorting ascending. Example from the blue skin:
th.headerSortUp {
  background-image: url(../img/small_asc.gif);
  background-color: #3399FF;
}
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. Example
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 "headerSortDown" The CSS style used to style the header when sorting descending. Example from the blue skin:
th.headerSortDown {
  background-image: url(../img/small_desc.gif);
  background-color: #3399FF;
}
cssHeader String "header" The CSS style used to style the header in its unsorted state. Example from the blue skin:
th.header {
  background-image: url(../img/small.gif);
  cursor: pointer;
  font-weight: bold;
  background-repeat: no-repeat;
  background-position: center left;
  padding-left: 20px;
  border-right: 1px solid #dad9c7;
  margin-left: -1px;
}
dateFormat String "us" Set the date format. Here are the available options:
  • "us" (default) - "mm-dd-yyyy" or "mm/dd/yyyy"
  • "uk" - "dd-mm-yyyy" or "dd/mm/yyyy"
  • "dd/mm/yy" or "dd-mm-yy" - Sort by short year (it appears to sort by day first, not the year)
debug Boolean false Boolean flag indicating if tablesorter should display debuging information usefull for development. 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).
$(function(){
  $("table").tablesorter({
    headers: {
      0: { sorter: false },      // disable first column - see Example 1
      1: { sorter: "digit" },    // sort second column numerically
      2: { sorter: "shortDate" } // sort the fifth column by date (e.g. mm/dd/yyyy if the date format is "us")
      3: { lockedOrder: "asc" },  // lock the sort order - this option will not work if added as metadata - see Example 2
      4: { sortInitialOrder: "desc" }, // Initial sort order direction of fourth column - see Example 3
    }
  });
});
Ex:1 2 3
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('span').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.
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.
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.
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" When clicking the header for the first time, the direction it sorts. Valid arguments are "asc" for Ascending or "desc" for Descending.
New! in v2.0.8: This order can also be set by desired column using the headers option.
Ex:1 2
sortLocaleCompare Boolean false Boolean flag indicating whenever to use javascript String.localeCampare method or not. This is only used when comparing text strings.
In Tablesorter version 2.0.6+, the default sort was replaced with an alpha-numeric sort. To over-ride this behaviour, set this sortLocaleCompare to true.
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: http://developer.mozilla.org/en/docs/DOM:event#Properties
Example
textExtraction String Or Function "simple" Defines which method is used to extract data from a table cell for sorting. Built-in options include "simple" and "complex". Use complex if you have data marked up inside of a table cell like: <td><strong><em>123 Main Street</em></strong></td>.
Complex can be slow in large tables so consider writing your own text extraction function "myTextExtraction" which you define like:
var myTextExtraction = function(node){
  // extract data from markup and return it
  // originally: return node.childNodes[0].childNodes[0].innerHTML;
  return $(node).text();
}
$(function(){
  $("#myTable").tableSorter( { textExtraction: myTextExtraction } );
});
tablesorter will pass a jQuery object containing the contents of the current cell 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.
$(function(){
  $("table").tablesorter({
    textExtraction: {
      1: function(node) {
           return $(node).find("span:last").text();
      }
    },
    headers: {
      1: { sorter : "digit" }
    }
  });
});
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
widgetZebra Object with Array {css:["even","odd"]} 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" ] }
  });
});
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

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):

Method Description Link
sorton Use this method to sort an initialized table in the desired order.
// Choose a new sort order
var sort = [[0,0],[2,0]];
// Note that the sort value below is inside of another array (inside another set of square brackets)
$("table").trigger("sorton", [sort]);
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
$("table").trigger("update");

// 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 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
    $("table").trigger("updateCell",[this]);

    // 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

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):

Event Description Link
sortStart This event fires when tablesorter is about to start resorting the table.
$(function(){

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

  // bind to sort events
  $("table")
    .bind("sortStart",function() {
      $("#overlay").show();
    })
    .bind("sortEnd",function() {
      $("#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() {
      $("#overlay").show();
    })
    .bind("sortEnd",function() {
      $("#overlay").hide();
    });
});
Example
pagerChange This event fires when the pager plugin begins to render the table on the currently selected page. New! in 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! in 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 jquery.tablesorter.zip

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

Support is available through the jQuery Mailing List.

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 and other changes added by Mottie.

John Resig for the fantastic jQuery