Author: Christian Bach
Version: 2.1+ (forked on github from version 2.0.5, changelog)
Licence:
Dual licensed under MIT
or GPL licenses.
Contents
- Introduction
- Demo
- Getting started
- Examples
- Configuration
- Widget & Pager Options (v2.1)
- Methods
- Events
- 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
- Multi-tbody sorting - see the options table below
- 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+
- Works with jQuery 1.2.6+ (jQuery 1.4.1+ needed with some widgets).
- Works with jQuery 1.9+ ($.browser.msie was removed; needed in the original version).
- 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:
<!-- choose a theme file --> <link rel="stylesheet" href="/path/to/theme.default.css"> <!-- load jQuery and tablesorter scripts --> <script type="text/javascript" src="/path/to/jquery-latest.js"></script> <script type="text/javascript" src="/path/to/jquery.tablesorter.js"></script> <!-- tablesorter widgets (optional) --> <script type="text/javascript" src="/path/to/jquery.tablesorter.widgets.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
Sorting
- Set an initial sorting order using options
- Sort table using a link outside the table
- Force a default sorting order
- Append a sort to the selected sorting order
- Child rows; how to add rows that sort with their parent row
- Child rows + filter widget; how they work together
- Direction of initial sort
- Disable sort
- Lock sort order
- Set initial sort order
- Using sortReset & sortRestart options
- Resetting the entire table sort (sortReset method) (v2.4.7)
- Using selectorSort option (v2.4)
- Sorting empty cells (v2.1.11)
- Change the default multi-sorting key
- Custom sort script (v2.2)
- Sorting Accented Characters (v2.24; languages)
- Sorting with Multiple Tbodies (v2.2)
- Sorting Across Multiple Columns (v2.3)
- Show a processing icon during sorting/filtering (v2.4)
Using Parsers / Extracting Content
- Dealing with digits!
- Dealing with text strings in numerical sorts (v2.0.10)
- Disable or set the column parser using class names (v2.0.11)
- Disable or set the column parser using jQuery Data (v2.3)
- Changing the date format (v2.0.23)
Plugins / Custom Widgets / Custom Parsers
-
Pager plugin
- Columns widget (v2.0.17)
- Content Editable widget (v2.9).
- Filter Widget:
- basic (v2.0.18; v2.10)
- custom (v2.3.6)
- formatter (jQuery UI widgets and HTML5 Elements) (v2.7.7).
- Grouping rows Widget (v2.8).
- Repeat Headers widget (v2.0.5; v2.9)
- Resizable Columns widget (v2.0.23.1; v2.8.3)
- Save sort widget (v2.0.27)
- Scroller widget (v2.9).
- Sticky header widget (v2.0.21.1; v2.10)
- UITheme widget:
- jQuery UI theme (v2.0.9; Modified v2.4)
- Bootstrap (v2.4)
-
Zebra stripe widget
- Assorted date parsers (v2.8).
- Ignore leading articles parser (Ignore "A", "An" and "The" in titles) (v2.8).
- Input/select parsers (used by Grouping rows widget) (v2.8).
- Metric parser (v2.8).
- Feet-inch-fraction parser (v2.8).
Advanced
Parsers / Extracting Content
- Parser, writing your own
- Parser, writing your own, advanced use (v2.1)
- Dealing with markup inside cells (textExtraction function)
Widgets / Plugins
- Applying widgets
- Widgets, writing your own
- Pager plugin - ajax (v2.1; v2.10)
- Pager plugin + filter widget (v2.4)
Adding / Removing Content
- Initializing tablesorter on a empty table
- Appending table data with ajax
- Adding a table row (v2.0.16)
- Update an entire table column (
thead
andtbody
) (v2.8). - Update the table after cell content has changed
- Pager plugin - examples of how to add and remove rows
Change Header Style
- UITheme widget (v2.0.9)
- Modifying the Header during rendering.
- Modifying the Header using a template (v2.7)
Other
Options & Events
- Triggers sortEnd and sortStart (Displaying sorting progress)
- Extending default options
- Enabling debug mode
Playgrounds & Other demos
- tablesorter basic demo (includes widgets)
- tablesorter basic demo using jQuery UI theme
- tablesorter basic demo with pager plugin
- tableSorter LESS theme; modify the colors dynamically in this LESS theme demo!
- Check out the home wiki page more demos!
Metadata - setting inline options
- *Note* you can use class names (version 2.0.11+, demo), or jQuery data (version 2.3+, demo) instead of meta data
- Set a initial sorting order using metadata.
- Disable header using metadata
- Setting column parser using metadata
Configuration
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-headerAsc" | The CSS style used to style the header when sorting ascending. Default value (changed v2.5).
Example from the blue theme:
.tablesorter-blue .tablesorter-headerAsc { background-color: #9fbfdf; background-image: url(black-asc.gif); } |
|||||||||||||||||||||||||
cssChildRow | String | "tablesorter-childRow" | 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. Previous default was "expand-child" (Changed in v2.4). | 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="tablesorter-childRow"> <!-- 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="tablesorter-childRow"> <!-- 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="tablesorter-childRow"> <!-- 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-headerDesc" | The CSS style used to style the header when sorting descending. Default value (changed v2.5).
Example from the blue theme:
.tablesorter-blue .tablesorter-headerDesc { background-color: #8cb3d9; 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 theme:
.tablesorter-blue .tablesorter-header { background-color: #99bfe6; background-repeat: no-repeat; background-position: center right; padding: 4px 20px 4px 4px; white-space: normal; cursor: pointer; } |
|||||||||||||||||||||||||
cssHeaderRow | String | "tablesorter-headerRow" | The CSS style used to style the header row (v2.4).
Previously the row would get the same class as the header cells, this class was added to make it easier to determine what element was being targetted in the plugin.
|
|||||||||||||||||||||||||
cssIcon | String | "tablesorter-icon" | The CSS style used to style the header cell icon (modified v2.7).
As of v2.4, an <i> element, with this class name, is automatically appended to the header cells. To prevent the plugin from adding an <i> element to the headers, set the cssIcon option to an empty string.In v2.7, the icon will only be added to the header if both the cssIcon option is set AND the headerTemplate option includes the icon tag ({icon} ).
|
|||||||||||||||||||||||||
cssProcessing | String | "tablesorter-processing" | This class name is added to the header cell that is currently being sorted or filted. To prevent this class name from being added, set the showProcessing option to false (v2.4). |
|||||||||||||||||||||||||
cssInfoBlock | String | "tablesorter-infoOnly" | All tbodies with this class name will not have its contents sorted. (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. |
|||||||||||||||||||||||||
dateFormat | String | "mmddyyyy" | Set the date format. Here are the available options. (Modified v2.0.23).
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 (they all do the same thing), set in order of priority (Modified v2.3.1):
|
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).
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 filter widget options for this column // See the "Applying the filter widget" demo 7: { filter: false }, // disable filter widget for this column 8: { filter: "parsed" }, // use parsed data for this column in the filter search // Set resizable widget options for this column 9: { resizable: false } // prevent resizing of column 9 } }); }); |
Ex:1 2 3 4 | ||||||||||||||||||||||||
headerTemplate | String | "{content}" | This is a template string which allows adding additional content to the header while it is being built (v2.7).
This template string has two modifying tags: {content} and {icon} .{content} will be replaced by the current header HTML content.{icon} will be replaced by <i class="tablesorter-icon"></i> , but only if a class name is defined in the cssIcon option.This template string may also contain HTML, e.g ( '<em>{content}</em> {icon}' )After the template string is built, the onRenderTemplate function is called to allow further manipulation. Please read more about this onRenderTemplate function and/or check out the example (link to the right).
|
Example | ||||||||||||||||||||||||
ignoreCase | Boolean | true | When true, text sorting will ignore the character case. If false, upper case characters will sort before lower case. (v2.2). | |||||||||||||||||||||||||
initWidgets | Boolean | true | Apply widgets after table initializes (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 after content is to the TH tags (after the template is procressed and added). 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 div with a class name of "tablesorter-inner" by default. In the example below, the header cell (TH) div is given a class name (source). $(function(){ $("table").tablesorter({ headerTemplate: '{content}', onRenderHeader: function (){ $(this).find('div').addClass('roundedCorners'); } }); });and you'll end up with this HTML (only the thead is shown) <thead> <tr> <th class="tablesorter-header"><div class="tablesorter-header-inner roundedCorners">Column 1</div></th> <th class="tablesorter-header"><div class="tablesorter-header-inner roundedCorners">Column 2</div></th> </tr> </thead>* Note: this function adds additional rendering time to the table if any DOM manipulation is done. Because this time will be on top of the processing time already added by the template. |
Example | ||||||||||||||||||||||||
onRenderTemplate | Function | null |
This function is called after the template string has been built, but before the template string is applied to the header and before the onRenderHeader function is called (v2.7).
The onRenderTemplate function receives a column index and template string parameters. The template string, from the headerTemplate option, will already have the {icon} and {content} tags replaced; it's just a string of formatted HTML. When done manipulating this string, return it. Here is an example:
$(function(){ $("table").tablesorter({ headerTemplate: '{icon}{content}', onRenderTemplate: function (index, template){ return '<em>' + (index + 1) + ':</em> ' + template; } }); });The template parameter can be manipulated as a string, or if you prefer, turn it into a jQuery object (var $t = $(template) ) to find and replace content as desired. Just make sure you return a string (return $t.html() )From the example function above, you'll end up with something similar to this HTML (only the thead is shown) <thead> <tr> <th class="tablesorter-header"><div class="tablesorter-header-inner"><em>1:</em> <i class="tablesorter-icon"></i>First Name</div></th> <th class="tablesorter-header"><div class="tablesorter-header-inner"><em>2:</em> <i class="tablesorter-icon"></i>Last Name</div></th> </tr> </thead>* Note: If the cssIcon option is an empty string, the {icon} tag will also become an empty string.
|
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). |
Ex:1 2 3 | ||||||||||||||||||||||||
selectorHeaders | String | "> thead th, > thead td" | jQuery selectors used to find cells in the header.
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 v2.3 to prevent targetting nested table headers. It was modified again in v2.4 to include td cells within the thead.
|
|||||||||||||||||||||||||
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. (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.
|
|||||||||||||||||||||||||
selectorSort | String | "th, td" | jQuery selector of content within selectorHeaders that is clickable to trigger a sort (v2.4). |
Example | ||||||||||||||||||||||||
serverSideSorting | Boolean | false | Set to true if the server is performing the sorting. The ui and events will still be used (v2.5.3). |
|||||||||||||||||||||||||
showProcessing | Boolean | false | Show an indeterminate timer icon in the header when the table is sorted or filtered. Please note that due to javascript processing, the icon may not show as being animated. I'm looking into this further and would appreciate any feedback or suggestions with the coding (v2.4). | Example | ||||||||||||||||||||||||
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.This option can also be set using jQuery data (v2.3.1) or metadata on the table:
|
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" |
This sets the direction a column will sort when clicking on 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 (they all do the same thing), set in order of priority (Modified v2.3.1):
|
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).
NOTE: See the Language wiki page for language specific examples and how to extend the character equivalent tables seen in the sortLocaleCompare demo. 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. (v2.0.27).
Don't confuse this option with the sortReset method. This option only resets the column sort after a third click, while the method immediately resets the entire table sort.
|
Example | ||||||||||||||||||||||||
sortResetKey | String | "ctrlKey" | The key used to reset sorting on the entire table. Defaults to the control key. The other options are "shiftKey" or "altKey" . Reference: https://developer.mozilla.org/en/DOM/MouseEvent |
|||||||||||||||||||||||||
sortRestart | Boolean | false |
Setting this option to true will start the sort with the sortInitialOrder when clicking on a previously unsorted column. (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" |
A key word indicating how tablesorter should deal with text inside of numerically sorted columns. (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:
|
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. |
|||||||||||||||||||||||||
theme | String | "default" | This option will add a theme css class name to the table "tablesorter-{theme}" for styling (v2.4).
When changing this theme option, make sure that the appropriate css theme file has also been loaded. Included theme files include: see all themes |
Example | ||||||||||||||||||||||||
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 Added $(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: (v2.1.3).
|
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 percentage-based widths to the table columns (modified v2.4).
Prior to v2.4, this option set pixel widths to added colgroups to fix the column widths. This is useful for the Pager companion.
|
Example | ||||||||||||||||||||||||
widgetOptions | Object | { } |
In 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. (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", "resizable", "stickyHeaders"], widgetOptions: { // *** columns widget *** // change the default column class names columns : [ "primary", "secondary", "tertiary" ], // include thead when adding class names columns_thead : true, // include tfoot when adding class names columns_tfoot : true, // *** filter widget *** // Include child rows content in the search filter_childRows : false, // show column filters filter_columnFilters : true, // css class applied to the filter row inputs/select filter_cssFilter : "tablesorter-filter", // class added to filtered rows; needed by pager plugin filter_filteredRow : 'filtered', // add custom filter elements to the filter row filter_formatter : null, // add custom filter functions using this option. filter_functions : null, // if true, the filter row is hidden initially until hovered/focused. filter_hideFilters : false, // if true, make all searches case-insensitive. filter_ignoreCase : true, // if true, search column content while the user types (with a delay) filter_liveSearch : true, // jQuery selector string of an element used to reset the filters. filter_reset : null, // typing delay in milliseconds before starting a search. filter_searchDelay : 300, // if true, filter start from the beginning of the cell contents. filter_startsWith : false, // filter all data using parsed content. filter_useParsedData : false, // Set to true for server-side filtering filter_serversideFiltering : false, // *** stickyHeaders widget *** // css class name applied to the sticky header stickyHeaders : "tablesorter-stickyHeader", // *** resizable widget *** // if false, resized columns are not saved for next page reload resizable : true, // if true, the last column will be resizable (use in non-full width tables) resizable_addLastColumn: false, // *** savesort widget *** // if false, the sort will not be saved for next page reload saveSort : true, // *** uitheme widget *** // include the name of the theme to use current options are // "jui" (default) and "bootstrap" uitheme : "jui", // *** zebra widget *** // class names to add, default is [ "even", "odd" ] zebra : ["ui-widget-content even", "ui-state-default odd"] } }); }); |
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)... (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. (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 & Pager Options
Widget Priority | Name | Requires jQuery | Limiting function |
---|---|---|---|
30 | columns | v1.2.6 | |
50 | filter | v1.4.3 | 1.4.3 (nextUntil) |
Last | pager | v1.2.6 | |
40 | resizable | v1.4.1* | 1.4 (isEmptyObject); 1.4.1 (parseJSON)* |
20 | saveSort | v1.4.1 | 1.4.1 (parseJSON)* |
60 | stickyHeaders | v1.2.6 | |
10 | uitheme | v1.2.6 | |
90 | zebra | v1.2.6 |
widgetOptions
. Thanks to thezoggy for putting together this jQuery-widget compatibility table, but please note:
- The applied order will not change depending on the widgets applied, but the numbers will change.
- The widgets are actually applied in reverse alphabetical order. This includes any custom widget names, so a custom widget named "zoom" will be the first applied widget. The only exception is the zebra widget which will always be the last widget applied.
- The pager, being a plugin, is actually initialized after tablesorter has initialized and all selected widgets applied.
- * The
saveSort
andresizable
widgets use the$.tablesorter.storage
function by default and thus need theparseJSON
function which is available in jQuery 1.4.1+.
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 | ||||||||||||||||
columns_thead | Boolean | true |
Columns widget: If true, the class names from the columns option will also be added to the table thead (v2.4).
Use the "columns_thead" option to add the column class names to the thead as follows:
$(function(){ $("table").tablesorter({ widgets: ["columns"], // initialize column styling of the table widgetOptions : { columns_thead: true } }); }); |
Example | ||||||||||||||||
columns_tfoot | Boolean | true |
Columns widget: If true, the class names from the columns option will also be added to the table tfoot (v2.4).
Use the "columns_tfoot" option to add the column class names to the tfoot as follows:
$(function(){ $("table").tablesorter({ widgets: ["columns"], // initialize column styling of the table widgetOptions : { columns_tfoot: true } }); }); |
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_columnFilters | Boolean | true |
Filter widget: If true , a filter will be added to the top of each table column (v2.4).
Use the filter_columnFilters option as follows:
$(function(){ $("table").tablesorter({ widgets: ["filter"], widgetOptions : { filter_columnFilters : true } }); }); |
|||||||||||||||||
filter_cssFilter | String | "tablesorter-filter" |
Filter widget: This is the class name applied to each input within the filter row (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" } }); });If you change it from the default class name of "tablesorter-filter" make sure you also update the css! |
Example | ||||||||||||||||
filter_filteredRow | String | "filtered" | Filter widget: This is the class name applied to all rows that match the filter; used by pager plugin (v2.10). | |||||||||||||||||
filter_formatter | Object | null |
Filter widget: This option allows you to add custom controls within the filter widget row (v2.7.7). A new file has been included named "jquery.tablesorter.widgets-filter-formatter.js". It includes code to add jQuery UI and HTML5 controls via the filter_formatter option.Most of the formatter functions have an option named valueToHeader which, when true adds a span to the header cell above the filter row and updates it with the current control's value (see example 2). If the option exists and is set to false , then the current value is added to the control's handle and css can be used to create a popup to show the current value (see example 1).Another custom option named addToggle is included with the "uiSpinner", "html5Color" and "html5Number" code. This allows the user to disable the control to show all table rows. For the single sliders, "uiSlider" and "html5Range", the minimum value is used to clear the filter (show all rows).The options included for each jQuery UI control only show basic options, but any or all of the jQuery UI options for that control can be included.
|
Ex: 1 2 | ||||||||||||||||
filter_functions | Object | null |
Filter widget: Customize the filter widget by adding a select dropdown with content, custom options or custom filter functions (v2.3.6).
Use the
"filter_functions" option in three different ways:
|
Example | ||||||||||||||||
filter_hideFilters | Boolean | false |
Filter widget: Set this option to true to hide the filter row initially. The row is revealed by hovering over the visible portion of the filter row or by giving any filter input/select focus (tab key) (v2.4).
Use the filter_hideFilters option as follows:
$(function(){ $("table").tablesorter({ widgets: ["filter"], widgetOptions : { filter_hideFilters : true } }); });You can change the style (thickness) of the hidden filter row in the tablesorter theme css. Look for .tablesorter-filter-row (revealed row) and .tablesorter-filter-row.hideme (for the hidden row) css definitions. |
Example | ||||||||||||||||
filter_ignoreCase | Boolean | true |
Filter widget: Set this option to false to make the column content search case-insensitive, so typing in "a" will not find "Albert". (v2.3.4)
Use the filter_ignorecase option as follows:
$(function(){ $("table").tablesorter({ widgets: ["filter"], widgetOptions : { filter_ignoreCase : false } }); }); |
Example | ||||||||||||||||
filter_liveSearch | Boolean, or Number | true |
Filter widget: If true , a search of the column content will occur as the user types, with the delay set in the filter_searchDelay option (v2.9; v2.10).
This option, when false allows you to disable the live search behavior, so that a filter is only applied when the user presses enter (or uses escape to clear and cancel the search).If this option is set to a number, e.g. 4 , a search of the column content will not initiate until this minimum number of characters are entered into the input.
|
|||||||||||||||||
filter_reset | String | null |
Filter widget: jQuery selector string of an element used to reset the filters (v2.4).
To use this option, point to a reset button or link using a jQuery selector. For example, add this button ( filter_reset option as follows:
$(function(){ $("table").tablesorter({ widgets: ["filter"], widgetOptions : { filter_reset : '.reset' } }); }); |
Example | ||||||||||||||||
filter_searchDelay | Numeric | 300 |
Filter widget: Set this option to the number of milliseconds to delay the search. (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);In tablesorter v2.4+, the trigger can be applied directly to the table: // refresh the widget filter; no delay $('table').trigger('search', false); |
|||||||||||||||||
filter_serversideFiltering | Boolean | false |
Filter widget: Set this option to true if filtering is performed on the server-side (v2.5.3).
Use the filter_serversideFiltering option as follows:
$(function(){ $("table").tablesorter({ widgets: ["filter"], widgetOptions : { filter_serversideFiltering : true } }); }); |
|||||||||||||||||
filter_startsWith | Boolean | false |
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. (v2.1).
Use the filter_startsWith option as follows:
$(function(){ $("table").tablesorter({ widgets: ["filter"], widgetOptions : { filter_startsWith : true } }); }); |
Example | ||||||||||||||||
filter_useParsedData | Boolean | false |
Filter widget: If true , ALL filter searches will only use parsed data (v2.4).
Use the filter_useParsedData option as follows:
$(function(){ $("table").tablesorter({ widgets: ["filter"], widgetOptions : { filter_useParsedData : false } }); });
|
|||||||||||||||||
stickyHeaders | String | "tablesorter-stickyHeader" |
Sticky Headers widget: This is the class name applied to the sticky header row (tr) (v2.1).
If you change it from the default class name of "tablesorter-stickyHeader" make sure you also update the css!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 | ||||||||||||||||
stickyHeaders_cloneId | String | "-sticky" |
Sticky Headers widget: If the table has an ID defined, the suffix from this option will be added to the ID in the cloned sticky table (v2.9).
So if your table ID is "gummy" , then the cloned sticky table id becomes "gummy-sticky" Use the "stickyHeaders_cloneId" option to change the cloned table id as follows:
$(function(){ $("table").tablesorter({ widgets: ["stickyHeaders"], widgetOptions : { // cloned table id suffix stickyHeaders_cloneId : "-clone" } }); }); |
|||||||||||||||||
stickyHeaders_offset | Multiple | 0 |
Sticky Headers widget: Set the sticky header offset from the top as a Number or jQuery selector string or object (v2.10).
If the page includes a fixed navigation bar at the top, like Bootstrap, set "stickyHeaders_offset" option to offset the sticky table header to be below the fixed navigation by setting this option using any of the following examples:$(function(){ $("table").tablesorter({ widgets: ["stickyHeaders"], widgetOptions : { // apply sticky header top 30px below the top of the browser window stickyHeaders_offset : 30 } }); });or stickyHeaders_offset : '.navbar-fixed-top' // jQuery selector stringor stickyHeaders_offset : $('.navbar-fixed-top') // jQuery object |
|||||||||||||||||
stickyHeaders_addResizeEvent | Boolean | true |
Sticky Headers widget: If true , sticky table headers will resize automatically when content is added to or removed from the table headers (v2.10).
While this option is true , a timer is initialized to check the width of every header cell every 1/4 second. If this causes lag, or any other problems, set this option to false .
When this option is false , sticky table headers are unable to detect and match the width of the original table headers when content is added or removed.Use the "stickyHeaders_addResizeEvent" option as follows:
$(function(){ $("table").tablesorter({ widgets: ["resizable"], widgetOptions : { // add header resize detection stickyHeaders_addResizeEvent : true } }); });When the browser window is resized, the headers (original and sticky) will resize automatically no matter the value of this option. |
|||||||||||||||||
resizable | Boolean | true |
Resizable widget: If this option is set to false , resized column widths will not be saved. Previous saved values will be restored on page reload (v2.4).
Use the "resizable" option to not save the resized widths:
$(function(){ $("table").tablesorter({ widgets: ["resizable"], widgetOptions : { // css class name applied to the sticky header resizable : false } }); }); |
Example | ||||||||||||||||
resizable_addLastColumn | Boolean | false |
Resizable widget: If this option is set to true , a resizing anchor will be included in the last column of the table (v2.8.3).
If an anchor was included and the table is full width, the column would resize in the opposite direction which my not be intuitive to the user. So set this option as desired, but please be mindful of the user experience. Use the "resizable_addLastColumn" option to include the last column resizer as follows:
$(function(){ $("table").tablesorter({ widgets: ["resizable"], widgetOptions : { // css class name applied to the sticky header resizable_addlastcolumn : true } }); }); |
Example | ||||||||||||||||
saveSort | Boolean | true |
saveSort widget: If this option is set to false , new sorts will not be saved. Any previous saved sort will be restored on page reload (v2.4).
Use the "saveSort" option to not save the current sort:
$(function(){ $("table").tablesorter({ widgets: ["saveSort"], widgetOptions : { // if false, the sort will not be saved for next page reload saveSort : false } }); }); |
Example | ||||||||||||||||
uitheme | String | "jui" |
This option contains the name of the theme. Currently jQuery UI ("jui") and Bootstrap ("bootstrap") themes are supported. To modify the class names used, extend from the theme (updated v2.4)
// Extend the themes to change any of the default class names ** NEW ** $.extend($.tablesorter.themes.jui, { // change default jQuery uitheme icons - find the full list of icons // here: http://jqueryui.com/themeroller/ (hover over them for their name) table : 'ui-widget ui-widget-content ui-corner-all', // table classes header : 'ui-widget-header ui-corner-all ui-state-default', // header classes footerRow : '', footerCells: '', icons : 'ui-icon', // icon class added to the <i> in the header sortNone : 'ui-icon-carat-2-n-s', sortAsc : 'ui-icon-carat-1-n', sortDesc : 'ui-icon-carat-1-s', active : 'ui-state-active', // applied when column is sorted hover : 'ui-state-hover', // hover class filterRow : '', even : 'ui-widget-content', // even row zebra striping odd : 'ui-state-default' // odd row zebra striping });This widget option replaces the previous widgetUitheme. All theme css names are now contained within the $.tablesorter.themes variable. Extend the default theme as seen above.The class names from the $.tablesorter.themes.{name} variable are applied to the table as indicated.As before the jQuery UI theme 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; Updated in v2.4). Find more jQuery UI class names by hovering over the Framework icons on this page: http://jqueryui.com/themeroller/Use the "uitheme" option to change the css class name as follows:
$(function(){ $("table").tablesorter({ theme : 'jui', // set theme name from $.tablesorter.themes here widgets : ["uitheme"], // initialize ui theme styling widget of the table widgetOptions: { uitheme : "jui" // this is now optional in v2.7, it is overridden by the theme option } }); });To add a new theme, define it as follows; replace "custom" with the name of your theme: $.tablesorter.themes.custom = { table : 'table', // table classes header : 'header', // header classes footerRow : '', footerCells: '', icons : 'icon', // icon class added to the <i> in the header sortNone : 'sort-none', // unsorted header sortAsc : 'sort-asc', // ascending sorted header sortDesc : 'sort-desc', // descending sorted header active : 'sort-active', // applied when column is sorted hover : 'hover', // hover class filterRow : 'filters', // class added to the filter row even : 'even', // even row zebra striping odd : 'odd' // odd row zebra striping } |
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 theme as follows:
$(function(){ $("table").tablesorter({ widgets: ["zebra"], // initialize zebra striping of the table widgetOptions: { zebra: [ "normal-row", "alt-row" ] } }); }); |
Example | ||||||||||||||||
Pager | ||||||||||||||||||||
container | Object | null |
Target your one or more pager markup blocks by setting this option with a jQuery selector.
This is some example pager markup. It should contain all of the controls set by the multiple css-named options: <div class="pager"> <form> <img src="first.png" class="first"/> <img src="prev.png" class="prev"/> <span class="pagedisplay"></span> <!-- this can be any element, including an input --> <img src="next.png" class="next"/> <img src="last.png" class="last"/> <select class="pagesize"> <option selected="selected" value="10">10</option> <option value="20">20</option> <option value="30">30</option> <option value="40">40</option> </select> <select class="gotoPage" title="Select page number"></select> </form> </div>Add this option as follows: $(function(){ $("table") .tablesorter() .tablesorterPager({ container: $(".pager") }); }); }); |
Example | ||||||||||||||||
ajaxUrl | String | null |
Set this option to include a url template to use so that the pager plugin can interact with your database (Added v2.1; v2.9).
Here is an example of how to include the option, it should always be paired with an ajaxProcessing function:
$(function(){ $("table") .tablesorter() .tablesorterPager({ ajaxUrl: "http://mydatabase.com?page={page}&size={size}&{sortList:col}&{filterList:fcol}", ajaxProcessing: function(ajax){ // do something with the ajax return [ formatted_data, total_rows ]; } }); }); });The ajaxUrl template replaces the following tags with values from the tablesorter plugin and pager addon:
|
Example | ||||||||||||||||
customAjaxUrl | Function | function(table, url) { return url; } |
This callback function allows you to modify the processed URL as desired (v2.8.1).
The customAjaxUrl function has two parameters, the table DOM element and the processed url string (all tags within the ajaxUrl have been replaced with their appropriate values).
$(function(){ $("table") .tablesorter() .tablesorterPager({ ajaxUrl: "http://mydatabase.com?page={page}&size={size}&{sortList:col}&{filterList:fcol}", ajaxProcessing: function(ajax){ // do something with the ajax return [ formatted_data, total_rows ]; }, // modify the url after all processing has been applied customAjaxUrl: function(table, url) { // trigger my custom event $(table).trigger('changingUrl'); // send the server the current page return url += '&currntUrl=' + window.location.href; }, }); }); }); |
Example | ||||||||||||||||
ajaxObject | Object | { dataType: 'json' } |
This option contains the ajax settings for the pager interaction with your database (v2.10).
The ajaxObject is completely customizable, except for the `url` setting which is processed using the pager's `ajaxUrl` and `customAjaxUrl` options.See all possible settings in the jQuery.ajax documentation $(function(){ $("table") .tablesorter() .tablesorterPager({ ajaxUrl: "http://mydatabase.com?page={page}&size={size}&{sortList:col}&{filterList:fcol}", ajaxObject: { // add more ajax settings here // see http://api.jquery.com/jQuery.ajax/#jQuery-ajax-settings dataType: 'json' }, ajaxProcessing: function(ajax){ // do something with the ajax; return [ total_rows ]; } }); }); }); |
Example | ||||||||||||||||
ajaxProcessing | Function | null |
This function is required to return the ajax data obtained from your server into a useable format for tablesorter to apply to the table (v2.1, v2.10).
In v2.10, the returned rows is now optional. And it can either be an array of arrays or a jQuery object (not attached to the table) Process your ajax data so that the following information is returned: // [ total_rows (number), rows (array of arrays), headers (array; optional) ] // or [ rows, total_rows, headers ] // or [ total_rows, $(rows) ] // or [ total_rows ] [ 100, // total rows [ [ "row1cell1", "row1cell2", ... "row1cellN" ], [ "row2cell1", "row2cell2", ... "row2cellN" ], ... [ "rowNcell1", "rowNcell2", ... "rowNcellN" ] ], [ "header1", "header2", ... "headerN" ] // optional ]Here is some example JSON (comments added, but not allowed in JSON) which is contained in the City0.json file: { // total rows "total_rows": 80, // headers "cols" : [ "ID", "Name", "Country Code", "District", "Population" ], // row data... "rows" : [{ "ID": 1, "Name": "Kabul", "CountryCode": "AFG", "District": "Kabol", "Population": 1780000 }, { // row 2, etc... }] }The above JSON is processed by the following code (this returns an array of array of table rows): $(function(){ $("table") .tablesorter() .tablesorterPager({ ajaxUrl: "http://mydatabase.com?page={page}&size={size}", ajaxProcessing: function(data){ if (data && data.hasOwnProperty('rows')) { var r, row, c, d = data.rows, // total number of rows (required) total = data.total_rows, // array of header names (optional) headers = data.cols, // all rows: array of arrays; each internal array has the table cell data for that row rows = [], // len should match pager set size (c.size) len = d.length; // this will depend on how the json is set up - see City0.json // rows for ( r = 0; r < len; r++ ) { row = []; // new row array // cells for ( c in d[r] ) { if (typeof(c) === "string") { row.push(d[r][c]); // add each table cell data to row array } } rows.push(row); // add new row array to rows array } return [ total, rows, headers ]; // or return [ rows, total, headers ] in v2.9+ } } }); });Or, in tablesorter v2.10, return a jQuery object ajaxProcessing: function(data, table){ if (data && data.hasOwnProperty('rows')) { var r, row, c, d = data.rows, // total number of rows (required) total = data.total_rows, // array of header names (optional) headers = data.headers, // all rows: array of arrays; each internal array has the table cell data for that row rows = '', // len should match pager set size (c.size) len = d.length; // this will depend on how the json is set up - see City0.json // rows for ( r=0; r < len; r++ ) { rows += '<tr class="ajax-row">'; // new row array // cells for ( c in d[r] ) { if (typeof(c) === "string") { rows += '<td>' + d[r][c] + '</td>'; // add each table cell data to row array } } rows += '</tr>'; // add new row array to rows array } // don't attach the $(rows) because it's difficult to tell old from new data // and no need to trigger an update method, it's done internally return [ total, $(rows), headers ]; } }Or, also in tablesorter v2.10, just build the table yourself and return the total number of rows: ajaxProcessing: function(data, table){ if (data && data.hasOwnProperty('rows')) { var r, row, c, d = data.rows, // total number of rows (required) total = data.total_rows, // all rows: array of arrays; each internal array has the table cell data for that row rows = '', // len should match pager set size (c.size) len = d.length; // this will depend on how the json is set up - see City0.json // rows for ( r=0; r < len; r++ ) { rows += '<tr class="ajax-row">'; // new row array // cells for ( c in d[r] ) { if (typeof(c) === "string") { rows += '<td>' + d[r][c] + '</td>'; // add each table cell data to row array } } rows += '</tr>'; // add new row array to rows array } // find first sortable tbody, then add new rows table.config.$tbodies.eq(0).html(rows); // no need to trigger an update method, it's done internally return [ total ]; } } |
Example | ||||||||||||||||
output | String | "{page}/{totalPages}" | This option allows you to format the output display which can show the current page, total pages, filtered pages, current start and end rows, total rows and filtered rows (v2.0.9). This option replaced the original separator option, which only separated the page number from the total number of pages. The formatted output from this option is placed inside the information block targeted by the cssPageDisplay option.Use it as follows: $(function(){ $("table") .tablesorter() .tablesorterPager({ output: '{startRow} to {endRow} of {totalRows} rows' }); }); });The following tags are replaced within the output string:
|
Ex: 1 2 3 4 | ||||||||||||||||
updateArrows | Boolean | true |
If true , the addon hides the left pager arrow on the first page and right pager arrow on the last page.
If true the classname from the cssDisabled option is applied to the arrows when at either page extreme. |
Example | ||||||||||||||||
page | Numeric | 0 | Set the starting page of the pager (zero-based index). | Example | ||||||||||||||||
size | Numeric | 10 | Set initial number of visible rows. This value is changed by the dropdown selector targeted by the cssPageSize option. |
Example | ||||||||||||||||
fixedHeight | Boolean | false | Maintain the height of the table even when fewer than the set number of records is shown (v2.1; updated 2.7.1).
This option replaced the original positionFixed and offset options which set the absolute position of the pager block.If true , it should maintain the height of the table, even when viewing fewer than the set number of records (go to the last page of any demo to see this in action). It works by adding an empty row to make up the differences in height.
|
Example | ||||||||||||||||
removeRows | Boolean | false |
If true , rows are removed from the table to speed up the sort of large tables (v2.0.21).
The original tablesorter plugin (v2.0.5) removed rows automatically, without providing an option. It really does speed up sorting of very large tables, but also breaks updating and modifying table content dynamically. If this option is false , the addon only hides the non-visible rows; this is useful if you plan to add/remove rows with the pager enabled.
|
Example | ||||||||||||||||
cssFirst | String | ".first" | This option contains a jQuery selector string pointing to the go to first page arrow. See container for full HTML. | Example | ||||||||||||||||
cssPrev | String | ".prev" | This option contains a jQuery selector string pointing to the go to previous page arrow. See container for full HTML. | Example | ||||||||||||||||
cssNext | String | ".next" | This option contains a jQuery selector string pointing to the go to next page arrow. See container for full HTML. | Example | ||||||||||||||||
cssLast | String | ".last" | This option contains a jQuery selector string pointing to the go to last page arrow. See container for full HTML. | Example | ||||||||||||||||
cssGoto | String | ".gotoPage" | This option contains a jQuery selector string pointing to the page select dropdown. See container for full HTML (v2.4)
Please note that this select dropdown is initially empty and automatically updated by the plugin with the correct number of pages, which depends on the size setting.
|
Example | ||||||||||||||||
cssPageDisplay | String | ".pagedisplay" | This option contains a jQuery selector string pointing to the output element (v2.0.9)
In the original tablesorter (v2.0.5) this option could only target an input, it was updated (v2.0.9) to display the formatted output from the output option inside of any element (span, div or input).
|
Example | ||||||||||||||||
cssPageSize | String | ".pagesize" | This option contains a jQuery selector string pointing to the page size selector. See container for full HTML. | Example | ||||||||||||||||
cssErrorRow | String | "tablesorter-errorRow" | This option contains the class name that is applied to the error information row that is added inside the pager with any ajax exceptions.
Note there is no period "." in front of this class name (it is not a selector). |
|||||||||||||||||
cssDisabled | String | "disabled" | This option contains the class name that is applied to disabled pager controls.
More explicitly, this class is applied to the pager arrows when they are at either extreme of pages and the updateArrows option is true . When the pager has been disabled, this class is applied to all controls.Note there is no period "." in front of this class name (it is not a selector). |
Methods
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. (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 |
sort | Use this method to initialize a sort while targeting a specific column header (v2.9).
// Target a specific header $('table').find('th:eq(2)').trigger('sort');Using this method will maintain the sorting order; so, if the column is already sorted in ascending order, this method will act as if you manually clicked on the header. Whatever sort order is applied is dependent on other option settings such as initialSortOrder , lockedOrder (set within the headers ), sortReset option, sortRestart and will be ignored if the column sort is disabled (sorter: false ). |
|
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 |
sortReset | Use this method to reset the table to it's initial unsorted state (v2.4.7).
Don't confuse this method with the
sortReset option. This method immediately resets the entire table sort, while the option only resets the column sort after a third click.
// Reset the table (make it unsorted) $("table").trigger("sortReset"); |
Example |
update / updateRow | Update the tbody 's stored data (update & updateRow do exactly the same thing)
// 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 after the update (if the "resort" flag is true // & will use the current sort selection), 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("update", [ false ]) .trigger("sorton", [sorting]); |
Example |
updateAll | Update a column of cells (thead and tbody ) (v2.8).
// Change thead & tbody column of cells // remember, "eq()" is zero based & "nth-child()" is 1 based $("table thead th:eq(2)").html("Number"); // add some random numbers to the table cell $("table tbody").find('td:nth-child(3)').html(function(i,h){ return Math.floor(Math.random()*10) + 1; // random number from 0 to 10 }); var resort = true, // re-apply the current sort callback = function(){ alert('table updated!'); }; // let the plugin know that we made a update, then the plugin will // automatically sort the table based on the header settings $("table").trigger("updateAll", [ resort, callback ]); |
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(){ // Do we want to reapply the current sort on the column? var resort = false, // Do something after the cell update in this callback function callback = function(table){ /* do something */ }, // randomize a number & add it to the cell discount = '$' + Math.round(Math.random() * Math.random() * 100) + '.' + ('0' + Math.round(Math.random() * Math.random() * 100)).slice(-2); // add new table cell text $(this).text(discount); // update the table, so the tablesorter plugin can update 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, 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 = [[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"]; // works the same as $("table")[0].config.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 // callback is a function $("table").trigger("destroy", [false, callback]); |
|
refreshWidgets | Refresh the currently applied widgets. Depending on the options, it will completely remove all widgets, then re-initialize the current widgets or just remove all non-current widgets (v2.4).
Trigger this method using either of the following methods (they are equivalent): // trigger a refresh widget event $('table').trigger('refreshWidgets', [doAll, dontapply]); // Use the API directly $.tablesorter.refreshWidgets(table, doAll, dontapply)
|
Example |
Widget Methods | ||
search | filter: Trigger the filter widget to update the search from current inputs and/or selections (v2.4).
This first method sends an array with the search strings to the filter widget.
$(function(){ // apply "2?%" filter to the fifth column (zero-based index) var columns = []; columns[4] = '2?%'; // or define the array this way [ '', '', '', '', '2?%' ] $('table').trigger('search', [columns]); });or, directly add the search string to the filter input as follows: $(function(){ // apply "2?%" filter to the fifth column (zero-based index) $('table').find('input.tablesorter-filter').eq(4).val('2?%'); $('table').trigger('search', false); // add a false flag to skip the search delay }); |
|
getFilters | filter: Get the currently applied filters in an array (v2.9):
$.tablesorter.getFilters( $('table') ); // or use $('table.hasFilters') to make sure the table has a filter rowThis method returns an array of filter values (e.g. [ '', '', '', '', '', '2?%' ] ) or false if the selected table does not have a filter row.
|
|
setFilters | filter: Set the filters using this method; include a true boolean to actually apply the search (v2.9):
// update filters, but don't apply the search $.tablesorter.setFilters( $('table'), [ '', '', '', '', '', '2?%' ] ); // update filters, AND apply the search $.tablesorter.setFilters( $('table'), [ '', '', '', '', '', '2?%' ], true ); // this will now use the search methodThis method returns true if the filters were sucessfully applied, or false if the table does not have a filter row.
|
|
filterReset | filter: Trigger the filter widget to reset the search criteria (v2.7.7).
If you are using the filter_formatter option to add custom input elements, this function may not work on those columns. Please refer to the filter_formatter section for more details.
$(function(){
// this is the same code that the |
Example |
addHeaderResizeEvent | Added a resize event to the table headers - used by the stickyHeaders widget, but this is a public function available to any widget (v2.10).
There is no built-in resize event for non-window elements, so when this function is active it triggers a resize event when the header cell changes size. So, if you are writing your own widget and need a header resize event, just include the jquery.tablesorter.widgets.js file, or just the extract the function from that file. Enable these triggered events as follows:
// Enable the triggering of header cell resize events as follows: var table = $('table')[0], disable = false, options = { timer : 250 // header cell size is checked every 250 milliseconds (1/4 of a second) }; $.tablesorter.addHeaderResizeEvent( table, disable, options );Then use it in your custom widget as follows: $(table).on('resize', function(event, columns){ // columns contains an array of header cells that were resized // this seemed like a better idea than firing off a resize event for every // column when the table adjusts itself to fit within its container event.stopPropagation(); // optional // do something console.log( columns ); });To disable these resize events, use this code: // Disable resize event triggering: var table = $('table')[0]; $.tablesorter.addHeaderResizeEvent( table, true ); |
|
saveSortReset | Trigger the saveSort widget to clear any saved sorts for that specific table (v2.7.11).
$(function(){ $('button').click(function(){ $('table').trigger('saveSortReset'); }); }); |
|
Pager Methods | ||
pageSize | Trigger the pager to change the page size (v2.7.4).
$(function(){ $('table').trigger('pageSize', 15); }); |
|
pageSet | Trigger the pager to change the current page (v2.7.7).
$(function(){ $('table').trigger('pageSet', 3); }); |
|
destroy.pager | Calling this method will reveal the entire table, remove the pager functionality, and hide the actual pager (v2.0.16).
$(function(){ $('table').trigger('destroy.pager'); });The only way to restore the pager is to re-initialize the pager addon $(function(){ $('table').tablesorterPager(pagerOptions); }); |
Example |
disable.pager | This method will put the pager into a disabled state (v2.0.21.2).
The disabled state will reveal all table rows and disable, but not hide, pager controls. $(function(){ $('table').trigger('disable.pager'); }); |
Example |
enable.pager | This method will re-enable the pager, but only from the disabled state (v2.0.21.2).
$(function(){ $('table').trigger('enable.pager'); }); |
Example |
Events
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. (v2.2).
$(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 |
updateComplete | This event fires after tablesorter has completed updating. (v.2.3.9)
This occurs after an "update", "updateAll", "updateCell" or "addRows" method was called, but before any callback functions are executed.
$(function(){ // initialize the tablesorter plugin $("table").tablesorter(); // bind to sort events $("table") .bind("updateComplete",function(e, table) { // do something after the table has been altered; }); }); |
|
Widget Events | ||
filterInit | Event triggered when the filter widget has finished initializing (v2.4).
You can use this event to modify the filter elements (row, inputs and/or selects) as desired. Use it as follows:
$(function(){ $('table').bind('filterInit', function(){ $(this).find('tr.tablesorter-filter-row').addClass('fred'); }); }); |
Example |
filterStart | Event triggered when the filter widget has started processing the search (v2.4).
You can use this event to do something like add a class to the filter row. Use it as follows:
$(function(){ $('table').bind('filterStart', function(){ $(this).find('tr.tablesorter-filter-row').addClass('filtering'); }); }); |
Example |
filterEnd | Event triggered when the filter widget has finished processing the search (v2.4).
You can use this event to do something like remove the class added to the filter row when the filtering started. Use it as follows:
$(function(){ $('table').bind('filterEnd', function(){ $(this).find('tr.tablesorter-filter-row').removeClass('filtering'); }); }); |
Example |
Pager Events | ||
pagerChange | This event fires when the pager plugin begins to render the table on the currently selected page. (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. (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 |
pagerBeforeInitialized | This event fires after all pager controls have been bound and set up but before the pager formats the table or loads any ajax data (v2.4.4).
$(function(){ $("table") // initialize the sorter .tablesorter() // bind to pager initialized event BEFORE calling the addon .bind('pagerBeforeInitialized', function(e, c){ // e = event object; c = pager options }) // initialize the pager plugin .tablesorterPager({ container: $("#pager") }); }); |
|
pagerInitialized | This event fires when the pager plugin has completed initialization (v2.4.4).
$(function(){ $("table") // initialize the sorter .tablesorter() // bind to pager initialized event BEFORE calling the addon .bind('pagerInitialized', function(e, c){ // c.totalPages contains the total number of pages $('#display').html( e.type + " event triggered, now on page " + (c.page + 1) ); }) // initialize the pager plugin .tablesorterPager({ container: $("#pager") }); }); |
Example |
pageMoved | This event fires when the pager plugin begins to change to the selected page (v2.4.4).
This event may fire before the
pagerComplete event when ajax processing is involved, or after the pagerComplete on normal use.
See issue #153.
$(function(){ // initialize the sorter $("table") .tablesorter() // initialize the pager plugin .tablesorterPager({ container: $("#pager") }) // bind to pager events .bind('pageMoved', 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:- jQuery (1.2.6 or higher; some demos & HTML5 data-attributes need jQuery 1.4.3+)
- jquery.tablesorter.min.js (19kb, minified for production - please put the file on your server)
- jQuery Metadata 2.1 (4kb, required for setting inline options)
- jquery.tablesorter.js (47kb/23kb min)
- jquery.tablesorter.pager.js (16kb/8kb min, demo)
- jquery.tablesorter.widgets.js (36kb/17kb min, includes the jQuery UI theme, columns styling, resizable columns, filter, sticky header and save sort widgets.
Theme zip files have been removed. There are now numerous themes available which can be seen here
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
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.
Some basic unit testing has been added. If you would like to add more or report a problem, please use the appropriate link above (v2.6).
Support is also available from stackoverflow.
For questions about jQuery, try irc, stackoverflow, or the jQuery forums.
Credits
Written by Christian Bach.
Documentation written by Brian Ghidinelli,
based on Mike Alsup's great documention.
Additional & Missing documentation, alphanumeric sort, numerous widgets, unit testing and other changes added by Mottie.
John Resig for the fantastic jQuery