Another option named ajaxProcessing was included to process the data before returning it to the pager plugin. Basically the JSON needs to contain the data to match the example below. An additional required variable is the total number of records or rows needs to be returned.
-
-
// process ajax so that the data object is returned along with the total number of rows
- // example: { "data" : [{ "ID": 1, "Name": "Foo", "Last": "Bar" }], "total_rows" : 100 }
- ajaxProcessing: function(ajax){
- if (ajax && ajax.hasOwnProperty('data')) {
- // return [ "data", "total_rows" ];
- return [ ajax.data, ajax.total_rows ];
- }
- }
-
-
I tried to make the plugin interact with a database as flexible as possible, but I'm sure I haven't covered every situation. So any and all feedback is welcome!
Added fixedHeight option which replaces the positionFixed and offset options.
-
-
-
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 to see this in action).
-
It works by adding an empty row to make up the differences in height.
-
There were some issues of the height being incorrect when this option is true. The problems occurred if you add/remove rows + change pager size, or just destroy/enable the pager. I think I fixed it, but if you should find a problem, please report the issue and steps on how to duplicate it.
-
-
-
-
The pager container option will now accept class names. So you can add multiple container blocks to control the pager, just as this page now has two, one above and one below.
-
The pager now adds all of its options to the table configuration options within an object named "pager". Basically what this means is that instead of add all of the pager options to be mixed in with the tablesorter options, the pager options have been isolated and can be found by typing this into the browser console: $('table')[0].config.pager.
Reduced the number of rows in the demo from 1022 to 50, so you don't have to scroll forever (when the pager is destroyed) to see the code below the table.
-
Added "destroy.pager" method will reveal the entire table, remove the pager functionality, and hide the actual pager.
-
Added a new addRows method to allow adding new rows while the pager is applied to a table. Using "update" would remove all non-visible rows.
Another option named ajaxProcessing was included to process the data before returning it to the pager plugin. Basically the JSON needs to contain the data to match the example below. An additional required variable is the total number of records or rows needs to be returned.
+
+
// process ajax so that the data object is returned along with the total number of rows
+ // example: { "data" : [{ "ID": 1, "Name": "Foo", "Last": "Bar" }], "total_rows" : 100 }
+ ajaxProcessing: function(ajax){
+ if (ajax && ajax.hasOwnProperty('data')) {
+ // return [ "data", "total_rows" ];
+ return [ ajax.data, ajax.total_rows ];
+ }
+ }
+
+
I tried to make the plugin interact with a database as flexible as possible, but I'm sure I haven't covered every situation. So any and all feedback is welcome!
Added fixedHeight option which replaces the positionFixed and offset options.
+
+
+
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 to see this in action).
+
It works by adding an empty row to make up the differences in height.
+
There were some issues of the height being incorrect when this option is true. The problems occurred if you add/remove rows + change pager size, or just destroy/enable the pager. I think I fixed it, but if you should find a problem, please report the issue and steps on how to duplicate it.
+
+
+
+
The pager container option will now accept class names. So you can add multiple container blocks to control the pager, just as this page now has two, one above and one below.
+
The pager now adds all of its options to the table configuration options within an object named "pager". Basically what this means is that instead of add all of the pager options to be mixed in with the tablesorter options, the pager options have been isolated and can be found by typing this into the browser console: $('table')[0].config.pager.
Reduced the number of rows in the demo from 1022 to 50, so you don't have to scroll forever (when the pager is destroyed) to see the code below the table.
+
Added "destroy.pager" method will reveal the entire table, remove the pager functionality, and hide the actual pager.
+
Added a new addRows method to allow adding new rows while the pager is applied to a table. Using "update" would remove all non-visible rows.
- 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:
-
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.
-
- 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.
-
-
- tablesorter has many options you can pass in at initialization to achieve different effects
- TIP! Click on the link in the property column to reveal full details (or toggle|show|hide all) or double click to update the browser location.
-
-
-
-
-
-
Property
-
Type
-
Default
-
Description
-
Link
-
-
-
-
-
Property
-
Type
-
Default
-
Description
-
Link
-
-
-
-
-
-
cancelSelection
-
Boolean
-
true
-
Indicates if tablesorter should disable selection of text in the table header (TH). Makes header behave more like a button.
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.
The CSS style used to style the header row. New! 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.
-
The CSS style used to style the header cell icon. New! v2.4.
-
- 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.
-
-
-
-
-
-
-
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. New! v2.4.
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.
-
Set the date format. Here are the available options. (Modified v2.0.23).
-
-
-
"mmddyyyy" (default)
-
"ddmmyyyy"
-
"yyyymmdd"
-
- In previous versions, this option was set as "us", "uk" or "dd/mm/yy". This option was modified to better fit needed date formats. It will only work with four digit years!
-
- The sorter should be set to "shortDate" and the date format can be set in the "dateFormat" option or set for a specific columns within the "headers" option.
- See the demo page to see it working.
-
$(function(){
- $("table").tablesorter({
-
- dateFormat : "mmddyyyy", // default date format
-
- // or to change the format for specific columns,
- // add the dateFormat to the headers option:
- headers: {
- 0: { sorter: "shortDate" }, // "shortDate" with the default dateFormat above
- 1: { sorter: "shortDate", dateFormat: "ddmmyyyy" }, // day first format
- 2: { sorter: "shortDate", dateFormat: "yyyymmdd" } // year first format
- }
-
- });
-});
- Individual columns can be modified by adding the following (they all do the same thing), set in order of priority (Modified v2.3.1):
-
-
jQuery data data-dateFormat="mmddyyyy".
-
metadata class="{ dateFormat: 'mmddyyyy'}". This requires the metadata plugin.
- 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.
-
- 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
- 9: { filter: "noquicksearch" } // exclude this column from the advanced filter quick search
-
- }
- });
-});
- 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.
-
Sort by the sorter value in the metadata - requires the metadata plugin.
-
- Check out the headers option to see how to use these parsers in your table (example #1). Or add a header class name using "sorter-" plus the parser name (example #2), this includes custom parsers (example #3).
-
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. Modified! v2.4.
-
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. New! v2.4.
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. New! v2.4.
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:
-
-
sortForce forces the user to have this/these column(s) sorted first (null by default).
-
SortList is the initial sort order of the columns.
-
SortAppend is the default sort that is added to the end of the users sort selection (null by default).
-
- The value of these sort options is an array of arrays and can include one or more columns. The format is an array of instructions for per-column sorting and direction in the format: [[columnIndex, sortDirection], ... ] where columnIndex is a zero-based index for your columns left-to-right and sortDirection is 0 for Ascending and 1 for Descending. A valid argument that sorts ascending first by column 1 and then column 2 looks like: [[0,0],[1,0]].
-
$(function(){
- $("table").tablesorter({
- sortForce : [[0,0]], // Always sort first column first
- sortList : [[1,0], [2,0]], // initial sort columns (2nd and 3rd)
- sortAppend : [[3,0]] // Always add this sort on the end (4th column)
- });
-});
-
- 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:
-
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.
-
- The direction a column sorts when clicking the header for the first time. Valid arguments are "asc" for Ascending or "desc" for Descending.
-
-
- This order can also be set by desired column using the headers option (Added in v2.0.8).
-
- Individual columns can be modified by adding the following (they all do the same thing), set in order of priority (Modified v2.3.1):
-
-
jQuery data data-sortInitialOrder="asc".
-
metadata class="{ sortInitialOrder: 'asc'}". This requires the metadata plugin.
- Boolean flag indicating if certain accented characters within the table will be replaced with their equivalent characters. (Modified v2.2).
-
-
-
This option no longer switches the sort to use the String.localeCompare method.
-
When this option is true, the text parsed from table cells will convert accented characters to their equivalent to allow the alphanumeric sort to properly sort.
-
If false (default), any accented characters are treated as their value in the standard unicode order.
-
The following characters are replaced for both upper and lower case (information obtained from sugar.js sorting equivalents table):
-
-
áàâãä replaced with a
-
ç replaced with c
-
éèêë replaced with e
-
íìİîï replaced with i
-
óòôõö replaced with o
-
úùûü replaced with u
-
ß replaced with S
-
-
-
Please see the example page for instrcutions on how to modify the above equivalency table.
-
If you would like to continuing using the String.localeCompare method, then set the sortLocaleCompare option to false and use the new textSorter option as follows:
-
- NOTE: See the Language wiki page for language specific examples and how to extend the character equivalent tables seen in the sortLocaleCompare demo.
-
- Boolean flag indicating whenever to use javascript String.localeCompare method or not.
- This is only used when comparing text with international character strings. A sort using localeCompare will sort accented characters the same as their unaccented counterparts.
-
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
This option will add a theme css class name to the table "tablesorter-{theme}" for styling. New 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
-
-
-
Defines which method is used to extract data from a table cell for sorting.
- The built-in option is "simple" which is the equivalent of doing this inside of the textExtraction function: $(node).text();.
-
-
- You can customize the text extraction by writing your own text extraction function "myTextExtraction" which you define like:
-
var myTextExtraction = function(node, table, cellIndex){
- // extract data from markup and return it
- // originally: return node.childNodes[0].childNodes[0].innerHTML;
- return $(node).find('selector').text();
-}
-$(function(){
- $("#myTable").tableSorter( { textExtraction: myTextExtraction } );
-});
- tablesorter will pass the current table cell object for you to parse and return. Thanks to Josh Nathanson for the examples. Updated to a jQuery example by Rob G (Mottie).
-
Now if the text you are finding in the script above is say a number, then just include the headers sorter option to specify how to sort it. Also in this example, we will specify that the special textExtraction code is only needed for the second column ("1" because we are using a zero-based index). All other columns will ignore this textExtraction function.
-
Added table and cellIndex variables to the textExtraction function in version 2.1.2.
- 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 ).
-
- 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.
-
- Requires the jQuery dimension plugin to work. This is now part of the jQuery core.
-
- 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",
- // 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,
- // 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,
-
- // *** 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,
-
- // *** 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"]
-
- }
-
- });
-});
- 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:
-
- 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:
-
- 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:
-
-
- tablesorter widgets have many options, and to better organize them, they now are grouped together inside of the 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 and resizable widgets use the $.tablesorter.storage function by default and thus need the ParseJSON 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.
-
- 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:
-
- 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:
-
- Filter widget: This is the class name applied to each input within the filter row. If you change it from the default class name of "tablesorter-filter" make sure you also update the css! (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"
- }
- });
-});
- Make a sorted select dropdown list of all column contents. Repeated content will be combined.
-
$(function(){
- $("table").tablesorter({
- widgets: ["filter"],
- widgetOptions: {
- filter_functions: {
- // Add select menu to this column
- // set the column value to true, and/or add "filter-select" class name to header
- 0 : true
- }
- }
- });
-});
- Alternately, instead of setting the column filter funtion to true, give the column header a class name of "filter-select". See the demo.
-
-
- Make a select dropdown list with custom option settings. Each option must have a corresponding function which returns a boolean value; return true if there is a match, or false with no match.
-
-
Regex example
-
$(function(){
- $("table").tablesorter({
- widgets: ["filter"],
- widgetOptions: {
- // function variables:
- // e = exact text from cell
- // n = normalized value returned by the column parser
- // f = search filter input value
- // i = column index
- filter_functions: {
- // Add these options to the select dropdown (regex example)
- 2 : {
- "A - D" : function(e, n, f, i) { return /^[A-D]/.test(e); },
- "E - H" : function(e, n, f, i) { return /^[E-H]/.test(e); },
- "I - L" : function(e, n, f, i) { return /^[I-L]/.test(e); },
- "M - P" : function(e, n, f, i) { return /^[M-P]/.test(e); },
- "Q - T" : function(e, n, f, i) { return /^[Q-T]/.test(e); },
- "U - X" : function(e, n, f, i) { return /^[U-X]/.test(e); },
- "Y - Z" : function(e, n, f, i) { return /^[Y-Z]/.test(e); }
- }
- }
- }
- });
-});
-
Comparison example
-
$(function(){
- $("table").tablesorter({
- widgets: ["filter"],
- widgetOptions: {
- // function variables:
- // e = exact text from cell
- // n = normalized value returned by the column parser
- // f = search filter input value
- // i = column index
- filter_functions: {
- // Add these options to the select dropdown (numerical comparison example)
- // Note that only the normalized (n) value will contain numerical data
- // If you use the exact text, you'll need to parse it (parseFloat or parseInt)
- 4 : {
- "< $10" : function(e, n, f, i) { return n < 10; },
- "$10 - $100" : function(e, n, f, i) { return n >= 10 && n <=100; },
- "> $100" : function(e, n, f, i) { return n > 100; }
- }
- }
- }
- });
-});
- Note: if the filter_ignoreCase option is true, it DOES alter the normalized value (n) by making it all lower case.
-
-
- Make a custom filter for the column.
-
$(function(){
- $("table").tablesorter({
- widgets: ["filter"],
- widgetOptions: {
- // function variables:
- // e = exact text from cell
- // n = normalized value returned by the column parser
- // f = search filter input value
- // i = column index
- filter_functions: {
- // Exact match only
- 1 : function(e, n, f, i) {
- return e === f;
- }
- }
- }
- });
-});
- Note: if the filter_ignoreCase option is true, it DOES alter the normalized value (n) by making it all lower case.
- Filter widget: Set this option to true to hide the filter row initially. The rows is revealed by hovering over the filter row or giving any filter input/select focus. New! v2.4.
-
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.
- Filter widget: jQuery selector string of an element used to reset the filters. New! v2.4.
-
-
- To use this option, point to a reset button or link using a jQuery selector. For example, add this button (<button class="reset">Reset</button>) to the table header, or anywhere else on the page. That element will be used as a reset for all column and quick search filters (clears all fields):
-
-
- 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 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).
-
To only use parsed data in specific columns, set this option to false and use any of the following (they all do the same thing), set in order of priority:
-
-
jQuery data data-filter="parsed".
-
metadata class="{ filter: 'parsed'}". This requires the metadata plugin.
- Sticky Headers widget: This is the class name applied to the sticky header row (tr). If you change it from the default class name of "tablesorter-stickyHeader" make sure you also update the css! (v2.1).
-
-
- Use the "stickyHeaders" option to change the css class name as follows:
-
$(function(){
- $("table").tablesorter({
- widgets: ["stickyHeaders"],
- widgetOptions : {
- // css class name applied to the sticky header
- stickyHeaders : "tablesorter-stickyHeader"
- }
- });
-});
- 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. New! v2.4.
-
-
- Use the "resizable" option to change the css class name as follows:
-
$(function(){
- $("table").tablesorter({
- widgets: ["resizable"],
- widgetOptions : {
- // css class name applied to the sticky header
- resizable : false
- }
- });
-});
- 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. New! v2.4.
-
-
- Use the "saveSort" option to change the css class name as follows:
-
$(function(){
- $("table").tablesorter({
- widgets: ["saveSort"],
- widgetOptions : {
- // if false, the sort will not be saved for next page reload
- saveSort : false
- }
- });
-});
- ** Updated! in tablesorter v2.4 **
-
- Instead of the array of icon class names, this option now 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
-
-
-
// 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
- 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:
-
- 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:
-
-
- tablesorter has some methods available to allow updating, resorting or applying widgets to a table after it has been initialized.
-
- TIP! Click on the link in the method column to reveal full details (or toggle|show|hide all) or double click to update the browser location.
-
- 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]);
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]);
Update the stored tablesorter data and the table.
-
-
// Add new content
-$("table tbody").append(html);
-
-// let the plugin know that we made a update
-// the resort flag set to anything BUT false (no quotes) will trigger an automatic
-// table resort using the current sort
-// A callback method was added in 2.3.9.
-var resort = true,
- callback = function(table){
- alert('new sort applied');
- };
-$("table").trigger("update", [resort, callback]);
-
-// As of version 2.0.14, the table will automatically resort (using the current sort selection)
-// after the update, so include the following if you want to specify a different sort
-
-// set sorting column and direction, this will sort on the first and third column
-var sorting = [[2,1],[0,0]];
-$("table").trigger("sorton", [sorting]);
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");
$(function() {
- $("table").tablesorter();
-
- $("td.discount").click(function(){
-
- // randomize a number
- var resort = false,
- discount = '$' + Math.round(Math.random() * Math.random() * 100) + '.' +
- ('0' + Math.round(Math.random() * Math.random() * 100)).slice(-2);
- // 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]);
-
- // 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;
- });
-});
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']);
- });
-
-});
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');
-
Use this method to remove tablesorter from the table.
-
-
// Remove tablesorter and all classes
-$("table").trigger("destroy");
-
-// Remove tablesorter and all classes but the "tablesorter" class on the table
-$("table").trigger("destroy", [false];
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. New 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)
-
-
If doAll is true it removes all widgets from the table. If false only non-current widgets (from the widgets option) are removed.
-
When done removing widgets, the widget re-initializes the currently selected widgets, unless the dontapply parameter is true leaving the table widget-less.
-
Note that if the widgets option has any named widgets, they will be re-applied to the table when it gets resorted. So if you want to completely remove all widgets from the table, also clear out the widgets option $('table')[0].config.widgets = [];
Trigger the filter widget to update the search from current inputs and/or selections. Updated! 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
-});
-
- tablesorter has some methods available to allow updating, resorting or applying widgets to a table after it has been initialized.
-
- TIP! Click on the link in the event column to reveal full details (or toggle|show|hide all) or double click to update the browser location.
-
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
- }
- });
-
-});
jquery.tablesorter.widgets.js (36kb/17kb min, includes the jQuery UI theme, columns styling, resizable columns, filter, sticky header and save sort widgets.
-
-
- Themes:
-
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:
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.
- Additional & Missing documentation, alphanumeric sort, numerous widgets and other changes added by Mottie.
-
+ 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:
+
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.
+
+ 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.
+
+
+ tablesorter has many options you can pass in at initialization to achieve different effects
+ TIP! Click on the link in the property column to reveal full details (or toggle|show|hide all) or double click to update the browser location.
+
+
+
+
+
+
Property
+
Type
+
Default
+
Description
+
Link
+
+
+
+
+
Property
+
Type
+
Default
+
Description
+
Link
+
+
+
+
+
+
cancelSelection
+
Boolean
+
true
+
Indicates if tablesorter should disable selection of text in the table header (TH). Makes header behave more like a button.
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.
The CSS style used to style the header row. New! 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.
+
The CSS style used to style the header cell icon. New! v2.4.
+
+ 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.
+
+
+
+
+
+
+
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. New! v2.4.
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.
+
Set the date format. Here are the available options. (Modified v2.0.23).
+
+
+
"mmddyyyy" (default)
+
"ddmmyyyy"
+
"yyyymmdd"
+
+ In previous versions, this option was set as "us", "uk" or "dd/mm/yy". This option was modified to better fit needed date formats. It will only work with four digit years!
+
+ The sorter should be set to "shortDate" and the date format can be set in the "dateFormat" option or set for a specific columns within the "headers" option.
+ See the demo page to see it working.
+
$(function(){
+ $("table").tablesorter({
+
+ dateFormat : "mmddyyyy", // default date format
+
+ // or to change the format for specific columns,
+ // add the dateFormat to the headers option:
+ headers: {
+ 0: { sorter: "shortDate" }, // "shortDate" with the default dateFormat above
+ 1: { sorter: "shortDate", dateFormat: "ddmmyyyy" }, // day first format
+ 2: { sorter: "shortDate", dateFormat: "yyyymmdd" } // year first format
+ }
+
+ });
+});
+ Individual columns can be modified by adding the following (they all do the same thing), set in order of priority (Modified v2.3.1):
+
+
jQuery data data-dateFormat="mmddyyyy".
+
metadata class="{ dateFormat: 'mmddyyyy'}". This requires the metadata plugin.
+ 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.
+
+ 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
+ 9: { filter: "noquicksearch" } // exclude this column from the advanced filter quick search
+
+ }
+ });
+});
+ 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.
+
Sort by the sorter value in the metadata - requires the metadata plugin.
+
+ Check out the headers option to see how to use these parsers in your table (example #1). Or add a header class name using "sorter-" plus the parser name (example #2), this includes custom parsers (example #3).
+
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. Modified! v2.4.
+
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. New! v2.4.
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. New! v2.4.
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:
+
+
sortForce forces the user to have this/these column(s) sorted first (null by default).
+
SortList is the initial sort order of the columns.
+
SortAppend is the default sort that is added to the end of the users sort selection (null by default).
+
+ The value of these sort options is an array of arrays and can include one or more columns. The format is an array of instructions for per-column sorting and direction in the format: [[columnIndex, sortDirection], ... ] where columnIndex is a zero-based index for your columns left-to-right and sortDirection is 0 for Ascending and 1 for Descending. A valid argument that sorts ascending first by column 1 and then column 2 looks like: [[0,0],[1,0]].
+
$(function(){
+ $("table").tablesorter({
+ sortForce : [[0,0]], // Always sort first column first
+ sortList : [[1,0], [2,0]], // initial sort columns (2nd and 3rd)
+ sortAppend : [[3,0]] // Always add this sort on the end (4th column)
+ });
+});
+
+ 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:
+
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.
+
+ The direction a column sorts when clicking the header for the first time. Valid arguments are "asc" for Ascending or "desc" for Descending.
+
+
+ This order can also be set by desired column using the headers option (Added in v2.0.8).
+
+ Individual columns can be modified by adding the following (they all do the same thing), set in order of priority (Modified v2.3.1):
+
+
jQuery data data-sortInitialOrder="asc".
+
metadata class="{ sortInitialOrder: 'asc'}". This requires the metadata plugin.
+ Boolean flag indicating if certain accented characters within the table will be replaced with their equivalent characters. (Modified v2.2).
+
+
+
This option no longer switches the sort to use the String.localeCompare method.
+
When this option is true, the text parsed from table cells will convert accented characters to their equivalent to allow the alphanumeric sort to properly sort.
+
If false (default), any accented characters are treated as their value in the standard unicode order.
+
The following characters are replaced for both upper and lower case (information obtained from sugar.js sorting equivalents table):
+
+
áàâãä replaced with a
+
ç replaced with c
+
éèêë replaced with e
+
íìİîï replaced with i
+
óòôõö replaced with o
+
úùûü replaced with u
+
ß replaced with S
+
+
+
Please see the example page for instrcutions on how to modify the above equivalency table.
+
If you would like to continuing using the String.localeCompare method, then set the sortLocaleCompare option to false and use the new textSorter option as follows:
+
+ NOTE: See the Language wiki page for language specific examples and how to extend the character equivalent tables seen in the sortLocaleCompare demo.
+
+ Boolean flag indicating whenever to use javascript String.localeCompare method or not.
+ This is only used when comparing text with international character strings. A sort using localeCompare will sort accented characters the same as their unaccented counterparts.
+
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
This option will add a theme css class name to the table "tablesorter-{theme}" for styling. New 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
+
+
+
Defines which method is used to extract data from a table cell for sorting.
+ The built-in option is "simple" which is the equivalent of doing this inside of the textExtraction function: $(node).text();.
+
+
+ You can customize the text extraction by writing your own text extraction function "myTextExtraction" which you define like:
+
var myTextExtraction = function(node, table, cellIndex){
+ // extract data from markup and return it
+ // originally: return node.childNodes[0].childNodes[0].innerHTML;
+ return $(node).find('selector').text();
+}
+$(function(){
+ $("#myTable").tableSorter( { textExtraction: myTextExtraction } );
+});
+ tablesorter will pass the current table cell object for you to parse and return. Thanks to Josh Nathanson for the examples. Updated to a jQuery example by Rob G (Mottie).
+
Now if the text you are finding in the script above is say a number, then just include the headers sorter option to specify how to sort it. Also in this example, we will specify that the special textExtraction code is only needed for the second column ("1" because we are using a zero-based index). All other columns will ignore this textExtraction function.
+
Added table and cellIndex variables to the textExtraction function in version 2.1.2.
+ 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 ).
+
+ 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.
+
+ Requires the jQuery dimension plugin to work. This is now part of the jQuery core.
+
+ 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",
+ // 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,
+ // 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,
+
+ // *** 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,
+
+ // *** 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"]
+
+ }
+
+ });
+});
+ 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:
+
+ 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:
+
+ 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:
+
+
+ tablesorter widgets have many options, and to better organize them, they now are grouped together inside of the 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 and resizable widgets use the $.tablesorter.storage function by default and thus need the ParseJSON 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.
+
+ 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:
+
+ 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:
+
+ Filter widget: This is the class name applied to each input within the filter row. If you change it from the default class name of "tablesorter-filter" make sure you also update the css! (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"
+ }
+ });
+});
+ Make a sorted select dropdown list of all column contents. Repeated content will be combined.
+
$(function(){
+ $("table").tablesorter({
+ widgets: ["filter"],
+ widgetOptions: {
+ filter_functions: {
+ // Add select menu to this column
+ // set the column value to true, and/or add "filter-select" class name to header
+ 0 : true
+ }
+ }
+ });
+});
+ Alternately, instead of setting the column filter funtion to true, give the column header a class name of "filter-select". See the demo.
+
+
+ Make a select dropdown list with custom option settings. Each option must have a corresponding function which returns a boolean value; return true if there is a match, or false with no match.
+
+
Regex example
+
$(function(){
+ $("table").tablesorter({
+ widgets: ["filter"],
+ widgetOptions: {
+ // function variables:
+ // e = exact text from cell
+ // n = normalized value returned by the column parser
+ // f = search filter input value
+ // i = column index
+ filter_functions: {
+ // Add these options to the select dropdown (regex example)
+ 2 : {
+ "A - D" : function(e, n, f, i) { return /^[A-D]/.test(e); },
+ "E - H" : function(e, n, f, i) { return /^[E-H]/.test(e); },
+ "I - L" : function(e, n, f, i) { return /^[I-L]/.test(e); },
+ "M - P" : function(e, n, f, i) { return /^[M-P]/.test(e); },
+ "Q - T" : function(e, n, f, i) { return /^[Q-T]/.test(e); },
+ "U - X" : function(e, n, f, i) { return /^[U-X]/.test(e); },
+ "Y - Z" : function(e, n, f, i) { return /^[Y-Z]/.test(e); }
+ }
+ }
+ }
+ });
+});
+
Comparison example
+
$(function(){
+ $("table").tablesorter({
+ widgets: ["filter"],
+ widgetOptions: {
+ // function variables:
+ // e = exact text from cell
+ // n = normalized value returned by the column parser
+ // f = search filter input value
+ // i = column index
+ filter_functions: {
+ // Add these options to the select dropdown (numerical comparison example)
+ // Note that only the normalized (n) value will contain numerical data
+ // If you use the exact text, you'll need to parse it (parseFloat or parseInt)
+ 4 : {
+ "< $10" : function(e, n, f, i) { return n < 10; },
+ "$10 - $100" : function(e, n, f, i) { return n >= 10 && n <=100; },
+ "> $100" : function(e, n, f, i) { return n > 100; }
+ }
+ }
+ }
+ });
+});
+ Note: if the filter_ignoreCase option is true, it DOES alter the normalized value (n) by making it all lower case.
+
+
+ Make a custom filter for the column.
+
$(function(){
+ $("table").tablesorter({
+ widgets: ["filter"],
+ widgetOptions: {
+ // function variables:
+ // e = exact text from cell
+ // n = normalized value returned by the column parser
+ // f = search filter input value
+ // i = column index
+ filter_functions: {
+ // Exact match only
+ 1 : function(e, n, f, i) {
+ return e === f;
+ }
+ }
+ }
+ });
+});
+ Note: if the filter_ignoreCase option is true, it DOES alter the normalized value (n) by making it all lower case.
+ Filter widget: Set this option to true to hide the filter row initially. The rows is revealed by hovering over the filter row or giving any filter input/select focus. New! v2.4.
+
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.
+ Filter widget: jQuery selector string of an element used to reset the filters. New! v2.4.
+
+
+ To use this option, point to a reset button or link using a jQuery selector. For example, add this button (<button class="reset">Reset</button>) to the table header, or anywhere else on the page. That element will be used as a reset for all column and quick search filters (clears all fields):
+
+
+ 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 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).
+
To only use parsed data in specific columns, set this option to false and use any of the following (they all do the same thing), set in order of priority:
+
+
jQuery data data-filter="parsed".
+
metadata class="{ filter: 'parsed'}". This requires the metadata plugin.
+ Sticky Headers widget: This is the class name applied to the sticky header row (tr). If you change it from the default class name of "tablesorter-stickyHeader" make sure you also update the css! (v2.1).
+
+
+ Use the "stickyHeaders" option to change the css class name as follows:
+
$(function(){
+ $("table").tablesorter({
+ widgets: ["stickyHeaders"],
+ widgetOptions : {
+ // css class name applied to the sticky header
+ stickyHeaders : "tablesorter-stickyHeader"
+ }
+ });
+});
+ 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. New! v2.4.
+
+
+ Use the "resizable" option to change the css class name as follows:
+
$(function(){
+ $("table").tablesorter({
+ widgets: ["resizable"],
+ widgetOptions : {
+ // css class name applied to the sticky header
+ resizable : false
+ }
+ });
+});
+ 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. New! v2.4.
+
+
+ Use the "saveSort" option to change the css class name as follows:
+
$(function(){
+ $("table").tablesorter({
+ widgets: ["saveSort"],
+ widgetOptions : {
+ // if false, the sort will not be saved for next page reload
+ saveSort : false
+ }
+ });
+});
+ ** Updated! in tablesorter v2.4 **
+
+ Instead of the array of icon class names, this option now 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
+
+
+
// 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
+ 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:
+
+ 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:
+
+
+ tablesorter has some methods available to allow updating, resorting or applying widgets to a table after it has been initialized.
+
+ TIP! Click on the link in the method column to reveal full details (or toggle|show|hide all) or double click to update the browser location.
+
+ 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]);
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]);
Update the stored tablesorter data and the table.
+
+
// Add new content
+$("table tbody").append(html);
+
+// let the plugin know that we made a update
+// the resort flag set to anything BUT false (no quotes) will trigger an automatic
+// table resort using the current sort
+// A callback method was added in 2.3.9.
+var resort = true,
+ callback = function(table){
+ alert('new sort applied');
+ };
+$("table").trigger("update", [resort, callback]);
+
+// As of version 2.0.14, the table will automatically resort (using the current sort selection)
+// after the update, so include the following if you want to specify a different sort
+
+// set sorting column and direction, this will sort on the first and third column
+var sorting = [[2,1],[0,0]];
+$("table").trigger("sorton", [sorting]);
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");
$(function() {
+ $("table").tablesorter();
+
+ $("td.discount").click(function(){
+
+ // randomize a number
+ var resort = false,
+ discount = '$' + Math.round(Math.random() * Math.random() * 100) + '.' +
+ ('0' + Math.round(Math.random() * Math.random() * 100)).slice(-2);
+ // 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]);
+
+ // 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;
+ });
+});
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']);
+ });
+
+});
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');
+
Use this method to remove tablesorter from the table.
+
+
// Remove tablesorter and all classes
+$("table").trigger("destroy");
+
+// Remove tablesorter and all classes but the "tablesorter" class on the table
+$("table").trigger("destroy", [false];
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. New 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)
+
+
If doAll is true it removes all widgets from the table. If false only non-current widgets (from the widgets option) are removed.
+
When done removing widgets, the widget re-initializes the currently selected widgets, unless the dontapply parameter is true leaving the table widget-less.
+
Note that if the widgets option has any named widgets, they will be re-applied to the table when it gets resorted. So if you want to completely remove all widgets from the table, also clear out the widgets option $('table')[0].config.widgets = [];
Trigger the filter widget to update the search from current inputs and/or selections. Updated! 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
+});
+
+ tablesorter has some methods available to allow updating, resorting or applying widgets to a table after it has been initialized.
+
+ TIP! Click on the link in the event column to reveal full details (or toggle|show|hide all) or double click to update the browser location.
+
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
+ }
+ });
+
+});
jquery.tablesorter.widgets.js (36kb/17kb min, includes the jQuery UI theme, columns styling, resizable columns, filter, sticky header and save sort widgets.
+
+
+ Themes:
+
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:
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.
+ Additional & Missing documentation, alphanumeric sort, numerous widgets and other changes added by Mottie.
+