# tablesorter

## Sort2Hash Widget (Beta)

### Flexible client-side table sorting

Back to documentation

### Notes

- In v2.24.4,
  - Added a `getParam` (get URL parameter) & a `removeParam` utility function to help deal with parameters in the URL hash. See the "Functions" section below for more details.
  - Alex Weissman has also provided code for a custom hash transformation in this gist; this code sets hash parameters that include the table id & named columns, e.g. `&filter[table0][first_name]=foobar`.
- In v2.24.0, lots of changes were made:
  - Removed `sort2Hash_useHeaderText` and `sort2Hash_processHeaderText` options.
  - Added `sort2Hash_headerTextAttr` option to replace the above two options.
  - Added `sort2Hash_encodeHash`, `sort2Hash_decodeHash` and `sort2Hash_cleanHash` options to allow custom value to hash processing.
  - This widget now works with the pager & filter, so the hash now includes pager current page, pager page size and current filters in the hash.
  - Lots of internal tweaks.
- Added v2.22.4. Instead of using the saveSort widget, this widget updates the hash tag to allow saving & sharing a sort applied to a tablesorter table.
- Sort the tables in the demo below. Notice the changes made to the location hash, then reload the page to have the hash applied to the tables.
- This widget requires jQuery version 1.7+.
- This widget does NOT work with tablesorter v2.0.5.

### Options

### Sort2Hash widget default options (added inside of tablesorter `widgetOptions`)

TIP! Click on the link in the option column to reveal full details (or toggle|show|hide all) or double click to update the browser location.

Option | Default | Description
--- | --- | ---
sort2hash_hash | `'#'` | The hash should always be there. This option was added to allow setting extra hash parameters and/or hashbang or whatever.
sort2Hash_separator | `','` | Change the hash separator using this option. There are some limitations. In the location hash, the sort parameters are added as `&tableID=column,direction, ... ,column,direction` (no spaces). This option allows changing the column-direction separator, a comma by default, into the chosen separator. *NOTE* Do not set this option to use a hash (`#`), ampersand (`&`) or equal sign (`=`) as it will interfere with how the hash parameters are set up.
sort2Hash_tableId | `null` | Set an ID here to override the table id attribute. In the location hash, the sort parameters are added as `&tableID=column,direction, ... ,column,direction` (no spaces). The `tableID` is set by this option. This option setting is prioritized over the actual table ID attribute. If neither are set, the `tableID` will be set as the table's zero-based index on the page.
    sort2Hash_tableID > table.id attribute > table index
sort2Hash_headerTextAttr | `'data-header'` | Data attribute on header cell containing alternate column identifier added to location hash. This option replaces both `sort2Hash_useHeaderText` and `sort2Hash_processHeaderText` options. The contents of this attribute will be used in the hash to identify a sorted column. Use the header attribute as follows:
    <th data-header="first">First Name</th>
sort2Hash_directionText | `[ 0, 1 ]` | Set the direction text shown in the URL. Only the first two values will be used from this array. The first value is assigned to ascending sorts and the second is assigned to descending sorts. Use the option as follows:
    sort2Hash_directionText : [ 'asc', 'desc' ]
*NOTE* When converting the hash into a value, if the direction hash does not match the second value (`'desc'` in the example above), it will fallback to an ascending sort no matter what text in contained within the first value.
sort2Hash_overrideSaveSort | `false` | if `true`, the hash sort will override any stored sort (saveSort widget).
sort2Hash_replaceHistory | `false` | Change how the browser history is managed (v2.29.0) If `true`, all hash changes are not saved to browser history, so when the user presses the back arrow, they will be returned to the previous page. If `false`, all hash changes are preserved in the browser history, so when the user presses the back arrow, the hash will show the previous state, but the table won't update unless the page is refreshed.
sort2Hash_encodeHash | `null` | Add a function to create a custom hash (v2.24.4). The following example is a duplicate of the internal code that encodes the hash. Adapt to fit your needs:
    sort2Hash_encodeHash : function( config, tableId, component, value, rawValue ) {
      // config = table.config settings
      // tableId = processed table ID
      // component: 'sort', 'page', 'size' or 'filter'
      // value = string value that has encodeURIComponent applied
      // rawValue = value ( array or number )
      // return false to let the widget encode the string
      return '&' + component + '[' + tableId + ']=' + value;
    }
Return a string to add to the `window.location.hash` directly. If this function returns `false`, then the internal code will encode the hash for that component. This was done in case only one parameter needs special handling:
    sort2Hash_encodeHash : function( config, tableId, component, value, rawValue ) {
      // only the filter gets special handling
      if ( component === 'filter' ) {
        // if working with rawValue, make sure to use
        // encodeURIComponent on the results
        var newValue = encodeURIComponent( rawValue.join( '--' ) );
        return tableId + 'filter=' + newValue;
      }
      return false;
    }
sort2Hash_decodeHash | `null` | Add a function to process a custom hash (v2.24.4). The following example is a duplicate of the internal code that decodes the hash. Adapt to fit your needs:
    sort2Hash_decodeHash : function( config, tableId, component ) {
      // config = table.config settings
      // tableId = processed table ID
      // component: 'sort', 'page', 'size' or 'filter'
      // return false to let the widget decode the hash

      // $.tablesorter.sort2Hash.getParam( parameter, url ); function added in v2.24.4
      // parameter = desired parameter to extract
      // url (optional) = hash or href string to extract the parameter value from
      return $.tablesorter.sort2Hash.getParam( component + '[' + tableId + ']' ) || '';
    }
Return the component value or an empty string. If this function returns `false`, then the internal code will attempt to decode the hash for that component. This was done in case only one parameter needs special handling:
    sort2Hash_decodeHash : function( config, tableId, component ) {
      // only the filter gets special handling
      if ( component === 'filter' ) {
        return $.tablesorter.sort2Hash.getParam( tableId + 'filter' ) || '';
      }
      return false;
    }
sort2Hash_cleanHash | `null` | Add a function to remove a custom hash (v2.24.4). The following example is a duplicate of the internal code that removes unused values in the hash. Adapt to fit your needs:
    sort2Hash_cleanHash : function( config, tableId, component, hash ) {
      // removeParam function added v2.24.4
      return $.tablesorter.sort2Hash.removeParam( component + '[' + tableId + ']' );
    }
Return a string of the remaining components or an empty string. If this function returns `false`, then the internal code will attempt to clean the hash for that component. This was done in case only one parameter needs special handling:
    sort2Hash_cleanHash : function( config, tableId, component, hash ) {
      // config = table.config settings
      // tableId = processed table ID
      // component: 'sort', 'page', 'size' or 'filter'
      // return false to let the widget decode the hash

      if ( component === 'filter' ) {
        // removeParam function added v2.24.4
        return $.tablesorter.sort2Hash.removeParam( tableId + 'filter' );
        /* ORIGINAL METHOD, use if the "getParam" function doesn't work on your custom parameter
        var index,
          result = [],
          // regular expression to match the component & value
          regex = new RegExp( tableId + 'filter=([^&]*)' );
          // split hash into component parts
          parts = ( hash || '' ).slice(1).split( '&' ),
          len = parts.length;
        // cycle through each component part
        for ( index = 0; index < len; index++ ) {
          // if the component doesn't match the regular expression...
          if ( !regex.test( parts[ index ] ) ) {
            // then save it
            result.push( parts[ index ] );
          }
        }
        // if we still have something left, join the components back together
        // and return it so the next component can be processed
        // we don't update the window.location.hash, or the page jumps to the top!
        return result.length ? c.widgetOptions.sort2Hash_hash + result.join( '&' ) : '';
        */
      }
      return false;
    }
Deprecated/Removed Options
sort2Hash_useHeaderText | `false` | This option has been removed in v2.24.0! It has been replaced by `sort2Hash_headerTextAttr`. If `true`, text from the header is used instead of a zero-based column index. Please be aware that if the column text contains spaces or special characters, they will be encoded in the URL. So, `"First £$€¤¥¢ Name"` will become `"First%20%C2%A3$%E2%82%AC%C2%A4%C2%A5%C2%A2%20Name"`. This would make the hash very difficult to read. Further processing of this header cell text can be done using the `sort2Hash_processHeaderText` function.
sort2Hash_processHeaderText | `null` | This option has been removed in v2.24.0! It has been replaced by `sort2Hash_headerTextAttr`. If the `sort2Hash_useHeaderText` option is `true`, a function here will further process the header cell text. Use this function to perform any processing on the header cell text, as desired. At this point, the header cell text has not been encoded. Here is one example:
    sort2Hash_processHeaderText : function( text, config, columnIndex ) {
      // remove all non-alphanumeric characters (including spaces)
      return text.replace( /[^a-z0-9]/gi, '' );
    }
Another example:
    sort2Hash_processHeaderText : function( text, config, columnIndex ) {
      // completely custom text to use for the hash
      // this method assumes that the table layout is constant
      // (i.e. columns are not added, removed or rearranged)
      return [ 'first', 'last', 'age', 'total', 'disc', 'date' ][ columnIndex ];
    }

### Functions

### Sort2Hash utility functions (added to `$.tablesorter.sort2Hash`)

TIP! Click on the link in the function column to reveal full details (or toggle|show|hide all) or double click to update the browser location.

Function | Description
--- | ---
getParam | Get URL Parameter (getParam) function This function will extract the value of the name passed to the function. Use it as follows:
    // $.tablesorter.sort2Hash.getParam( name, hash );
    // name = parameter name (key)
    // hash = (optional) if undefined, it will get the string value from window.location.hash
    var hash = '&sort[table-users][user_name]=asc&page[table-users]=1&size[table-users]=10&filter[table-users][user_name]=ad',
    	result = $.tablesorter.sort2Hash.getParam( 'filter[table-users][user_name]', hash );
    // result = "ad";
removeParam | Remove parameter from hash This function will remove the key & value from the passed hash. Use it as follows:
    // $.tablesorter.sort2Hash.removeParam( name, hash );
    // name = parameter name (key)
    // hash = (optional) if undefined, it will get the string value from window.location.hash
    var hash = '&sort[table-users][user_name]=asc&page[table-users]=1&size[table-users]=10&filter[table-users][user_name]=ad',
    	result = $.tablesorter.sort2Hash.removeParam( 'filter[table-users][user_name]', hash );
    // result = "&sort[table-users][user_name]=asc&page[table-users]=1&size[table-users]=10";
*NOTE* This function does not update `window.location.hash`.

# Demo

### Basic Usage †

First Name | Last Name | Age | Total | Discount | Date
--- | --- | --- | --- | --- | ---
Peter | Parker | 28 | $9.99 | 20% | Jul 6, 2006 8:14 AM
John | Hood | 33 | $19.99 | 25% | Dec 10, 2002 5:14 AM
Clark | Kent | 18 | $15.89 | 44% | Jan 12, 2003 11:14 AM
Bruce | Almighty | 45 | $153.19 | 44% | Jan 18, 2001 9:12 AM
Bruce | Evans | 22 | $13.19 | 11% | Jan 18, 2007 9:12 AM

† This table shows up as "table4" because there is no ID assigned, and it is the fifth table (zero-based index) on the page. The first table is in the "Options" section. The second is actually the stickyheader table for "Options". The third & forth (sticky header) are in the "Functions" section.

### Data Header (Using symbols for headers)

First Name (^) | Last Name (&) | Age (#) | Total ($) | Discount (%) | Date (*)
--- | --- | --- | --- | --- | ---
Peter | Parker | 28 | $9.99 | 20% | Jul 6, 2006 8:14 AM
John | Hood | 33 | $19.99 | 25% | Dec 10, 2002 5:14 AM
Clark | Kent | 18 | $15.89 | 44% | Jan 12, 2003 11:14 AM
Bruce | Almighty | 45 | $153.19 | 44% | Jan 18, 2001 9:12 AM
Bruce | Evans | 22 | $13.19 | 11% | Jan 18, 2007 9:12 AM

### Pager (page & size)

Name | Major | Sex | English | Japanese | Calculus | Geometry
--- | --- | --- | --- | --- | --- | ---
Name | Major | Sex | English | Japanese | Calculus | Geometry
Student01 | Languages | male | 80 | 70 | 75 | 80
Student02 | Mathematics | male | 90 | 88 | 100 | 90
Student03 | Languages | female | 85 | 95 | 80 | 85
Student04 | Languages | male | 60 | 55 | 100 | 100
Student05 | Languages | female | 68 | 80 | 95 | 80
Student06 | Mathematics | male | 100 | 99 | 100 | 90
Student07 | Mathematics | male | 85 | 68 | 90 | 90
Student08 | Languages | male | 100 | 90 | 90 | 85
Student09 | Mathematics | male | 80 | 50 | 65 | 75
Student10 | Languages | male | 85 | 100 | 100 | 90
Student11 | Languages | male | 86 | 85 | 100 | 100
Student12 | Mathematics | female | 100 | 75 | 70 | 85
Student13 | Languages | female | 100 | 80 | 100 | 90
Student14 | Languages | female | 50 | 45 | 55 | 90
Student15 | Languages | male | 95 | 35 | 100 | 90
Student16 | Languages | female | 100 | 50 | 30 | 70
Student17 | Languages | female | 80 | 100 | 55 | 65
Student18 | Mathematics | male | 30 | 49 | 55 | 75
Student19 | Languages | male | 68 | 90 | 88 | 70
Student20 | Mathematics | male | 40 | 45 | 40 | 80
Student21 | Languages | male | 50 | 45 | 100 | 100
Student22 | Mathematics | male | 100 | 99 | 100 | 90
Student23 | Mathematics | male | 82 | 77 | 0 | 79
Student24 | Languages | female | 100 | 91 | 13 | 82
Student25 | Mathematics | male | 22 | 96 | 82 | 53
Student26 | Languages | female | 37 | 29 | 56 | 59
Student27 | Mathematics | male | 86 | 82 | 69 | 23
Student28 | Languages | female | 44 | 25 | 43 | 1
Student29 | Mathematics | male | 77 | 47 | 22 | 38
Student30 | Languages | female | 19 | 35 | 23 | 10
Student31 | Mathematics | male | 90 | 27 | 17 | 50
Student32 | Languages | female | 60 | 75 | 33 | 38
Student33 | Mathematics | male | 4 | 31 | 37 | 15
Student34 | Languages | female | 77 | 97 | 81 | 44
Student35 | Mathematics | male | 5 | 81 | 51 | 95
Student36 | Languages | female | 70 | 61 | 70 | 94
Student37 | Mathematics | male | 60 | 3 | 61 | 84
Student38 | Languages | female | 63 | 39 | 0 | 11
Student39 | Mathematics | male | 50 | 46 | 32 | 38
Student40 | Languages | female | 51 | 75 | 25 | 3
Student41 | Mathematics | male | 43 | 34 | 28 | 78
Student42 | Languages | female | 11 | 89 | 60 | 95
Student43 | Mathematics | male | 48 | 92 | 18 | 88
Student44 | Languages | female | 82 | 2 | 59 | 73
Student45 | Mathematics | male | 91 | 73 | 37 | 39
Student46 | Languages | female | 4 | 8 | 12 | 10
Student47 | Mathematics | male | 89 | 10 | 6 | 11
Student48 | Languages | female | 90 | 32 | 21 | 18
Student49 | Mathematics | male | 42 | 49 | 49 | 72
Student50 | Languages | female | 56 | 37 | 67 | 54

# Javascript

# HTML