Author: Christian Bach
Version: 2.0.14 (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: christian at tablesorter dot com.
Contents
- Introduction
- Demo
- Getting started
- Examples
- Configuration
- Methods New!
- Events New!
- Download
- Compatibility
- Support
- 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:
- Multi-column sorting
- Parsers for sorting text, URIs, integers, currency, floats, IP addresses, dates (ISO, long and short formats), time. Add your own easily
- Support secondary "hidden" sorting (e.g., maintain alphabetical sort when sorting on other criteria)
- Extensibility via widget system
- Cross-browser: IE 6.0+, FF 2+, Safari 2.0+, Opera 9.0+
- Small code size
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- Set an initial sorting order using options
- Sort table using a link outside the table
- How to add rows that sort with their parent row
- Force a default sorting order
- Append a sort to the selected sorting order
- Dealing with digits!
- Dealing with text strings in numerical sorts New! v2.0.10
- Direction of initial sort
- Applying widgets
- Applying the zebra stripe widget
- Applying the jQuery UI theme widget New! v2.0.9
- Disable or set the column parser using class names New! v2.0.11
- Disable sort using headers options
- Lock sort order using header options
- Set initial sort order using header options
- Change the default multi-sorting key
- Set a initial sorting order using metadata
- Disable header using metadata
- Setting column parser using metadata
- Triggers sortEnd and sortStart (Displaying sorting progress)
- Initializing tablesorter on a empty table
- Appending table data with ajax
- Update the table after cell content has changed
- Dealing with markup inside cells (textExtraction function)
- Modify how the header is rendered to allow for custom styling
- Extending default options
- Enabling debug mode
- Parser, writing your own
- Widgets, writing your own
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:
|
|||||||||||||||||||||||||
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). 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" }, // zero 2: { sorter: "digit", string: "max+" }, // maximum positive value 3: { sorter: "digit", string: "max-" }, // maximum negative value // Sort the fifth column by date (e.g. mm/dd/yyyy if the date format is "us") 4: { sorter: "shortDate" } // 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" } } }); }); |
Ex:1 2 3 4 | ||||||||||||||||||||||||
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:
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) New!. |
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. | |||||||||||||||||||||||||
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:
[[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.
|
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"); // 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 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]); // 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 |
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:- jQuery (1.2.1 or higher)
- jquery.tablesorter.min.js (12kb, Minified for production - please put the file on your server)
- jQuery Metadata 2.1 (3,7kb Required for setting inline options)
- jquery.tablesorter.js (17,7kb, for development)
- jquery.tablesorter.pager.js (3,6kb, tablesorter pagination plugin)
- Green Skin - Images and CSS styles for green themed headers
- Blue Skin - Images and CSS styles for blue themed headers (as seen in the examples)
- jQuery UI Theme - Apply any jQuery UI theme to the table using the "uitheme" widget code. New! in v2.0.9!
Browser Compatibility
tablesorter has been tested successfully in the following browsers with Javascript enabled:
- Firefox 2+
- Internet Explorer 6+
- Safari 2+
- Opera 9+
- Konqueror
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