jQuery tablesorter 2.0 - Column Selector Widget

# tablesorter

## Column Selector Widget

### Flexible client-side table sorting

Back to documentation

### Notes

- In v2.29.0, added a `columnSelector_classHasSpan` setting.
- In v2.27.0,
  - Added two new options: `columnSelector_maxVisible` and `columnSelector_minVisible`.
  - These settings set a maximum and/or minimum number of visible columns. Please see the option description for each setting for important details!
  - The `refreshColumnSelector` method is not constrained by these limitations. Only user interaction is restricted.
- In v2.25.9,
  - Added a `columnSelector_maxPriorities` setting.
  - Using the "refreshColumnSelector" method now properly saves the settings if the `columnSelector_saveColumns` is `true`.
  - The widget still uses the `filter_filteredRow` setting, but now falls back to using "filtered" when it is undefined.
- In v2.24.0,
  - This widget now supports extra rows and `colspan` cells in the header & footer (not the body). The first demo has been updated to show this enhancement.
  - Added `columnSelector_mediaqueryHidden` option.
- In v2.23.2, added `columnSelector_updated` option.
- In v2.23.0, updated methods to allow refreshing the content of the container & enchanced ability to set both auto and columns modes.
- In v2.19.0, the `refreshColumnSelector` method has been updated to allow passing a parameter. Pass an array of zero-based column indexes of columns to show, or any non-array to enable auto mode (if available).
- In v2.18.4, added `columnSelector_cssChecked` option which contains the class name added to checked inputs. This helps fix an issue in Chrome that rears it's ugly head when trying to use `input:checked` to change a Font Awesome icon. See this demo by TheSin which uses this option to change the checkbox style.
- In v2.17.0, a method to refresh the column selector was added.
- This widget will only work in tablesorter version 2.8+ and jQuery version 1.7+.
- This widget may not work properly if the table body contains rows with `rowspan` or `colspan` settings.
- The responsive part of this widget:
  - Uses similar parameters as those used by jQuery mobile to set column priority.
  - The column priorities range from 1 to 6, with 1 having the highest priority. As the browser window shrinks, lower priority (higher numbers) columns will be hidden first until all numbered priority columns are hidden.
  - Any named data-priority, other than the numbers 1 - 6, (e.g. "critical" or "persistent") will be treated as a column which will not be included in the column selector.
  - Note that this widget uses media queries, which will not work in IE8 and older browsers.
- The selector code uses css selectors, for optimal speed, to hide/show columns. These selectors will not work in IE8 and older browsers.
- The column button & popup is completely customizable, and in this demo it includes css that may not work properly in older versions of IE.

### Options

#### Column selector 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 | Description
--- | ---
- columnSelector_container | Target an element within the current page where the column selector will be inserted. This setting is optional. If not set, you can use the following function to attach it to another element - see the Bootstrap example below
      $.tablesorter.columnSelector.attachTo( $('table'), '.selector-target' );
This can be either a jQuery selector string ( e.g. `'#columnSelector'` ) or, a jQuery object ( e.g. `$('#columnSelector')` ). Default value: `null`
- columnSelector_columns | Assigns a column status for each selector To disable, or remove a column from the column selector, include the key word `"disable"` - this is one of many ways to remove a column from the column selector popup Set a column status to `true` to initially display a column. This is the default for undefined columns. Set a column status to `false` to initially hide a column. Examples:
      widgetOptions : {
        columnSelector_columns : {
          0 : "disable", /* disable; i.e. remove column from selector */
          1 : false,     /* start with column hidden */
          2 : true,      /* start with column visible; default for undefined columns */
        }
      }
*NOTE* Prior to v2.15.6, using these extra methods and setting a column to "false" would remove it from the selector. Now, it is more consistent with this columns option - set the appropriate method to "disable" to remove a column, "false" to initially hide a column and "true" to keep the column in an initially visible state. In v2.15.6, the following methods in order of priority are now available (set to true, false or disable): jQuery data `data-columnSelector="true"` or `data-columnSelector="false"`. metadata `class="{ columnSelector : true }"` or `class="{ columnSelector : false }"`. headers option `headers : { 0 : { columnSelector: true } }` or `headers : { 0 : { columnSelector: false } }`. header class name `class="columnSelector-true"` or `class="columnSelector-false"`. *NOTE* Setting a column to initially be visible (`true`) or invisible (`false`) will be overridden by the users saved selections if the `columnSelector_saveColumns` option is `true`. NOTE If only using this widget to hide columns, set the `columnSelector_mediaquery` option to `false`. Otherwise, you'll also need to set a `data-priority` in each column header. Default value: `{}`; empty object
columnSelector_saveColumns | Save the current manually set column status and the table's responsive ("auto") state (v2.15.7). This option requires the storage utility contained within the tablesorter widgets file (`jquery.tablesorter.widgets.js`). Default value: `true`
columnSelector_layout | This option defines the markup used for each column selector within the popup. The only available parameter is the `{name}` string which will be replaced with the appropriate column name/title. An `<input type="checkbox">` is required within this setting! The label element is optional. Default value: `'<label><input type="checkbox">{name}</label>'`
columnSelector_layoutCustomizer | This option is set as a callback function that is called during the processing of the layout for each column. This callback contains three parameters: `$cell` - jQuery object pointing to the header cell inner wrapper. If the `headerTemplate` option is set as an empty string, then the inner wrapper is not included, and the `$cell` would then point to the table cell (`th` or `td` depending on the markup). `name` - This parameter contains the header cell title string. This value is obtained from the header cell `data-selector-name` attribute, if defined, or the header cell text. `index` - The current column index as a number value.
    $(function() {
      $("#task").tablesorter({
        widgets: ["columnSelector"],
        widgetOptions: {
          columnSelector_container: $('#columnSelector'),
          columnSelector_layoutCustomizer: function($cell, name, index) {
            // return the HTML for the first column only
            return index === 0 ? $cell.html() : name;
          }
        }
      });
    });
Default value: `null`
columnSelector_name | The data-attribute within the table header cell which contains an alternate column selector name. If the header cell does not have this attribute defined, the column selector name will be taken from the header cell internal text. If defined, the text contained within this attribute will replace the `{name}` string within the layout option above. Default value: `'data-selector-name'`
columnSelector_mediaquery | Set this option to add (`true`) or not add (`false`) the media query functionality of this widget. When `true`, an "auto" checkbox is included along with the column checkboxes: When the "auto" checkbox is checked, all column checkboxes are disabled and media queries are active (columns will hide or show based on the browser width). If "auto" is unchecked, media queries are disabled and column (non-critial/not disabled) visibility is based on the column checkbox setting. Note When set to `true`, this option requires the `data-priority` attributes (name set by the `columnSelector_priority` option) be set in each header column
    <th data-priority="critical">Rank</th>
See `columnSelector_priority` for more details. Default value: `true`
columnSelector_mediaqueryName | When the media query checkbox is added (it also uses the `columnSelector_layout` markup), this is the name that is added. Set as "Auto" to signify to the user that columns disappearing and/or reappearing is automatically done. Default value: `'Auto: '`
columnSelector_mediaqueryState | Set this option to `false` to start with the media query disabled (manual column selection mode). Default value: `true`
columnSelector_mediaqueryHidden | When this option is set to `true` columns with a "columnSelector-false" class will be hidden while media queries ("auto" mode) are active (v2.24.0). With this option set to `true`, the hidden state of a column can be set using any of the following methods, added to the header cell, in order of priority: jQuery data `data-columnSelector="false"`. metadata `class="{ columnSelector : false }"` (requires the metadata plugin). headers option `headers : { 0 : { columnSelector: 'false' } }`. header class name `class="columnSelector-false"`. See issue #964 for more details. Default value: `false`
columnSelector_maxVisible | Set this option to a number to set a maximum number of visible columns (v2.27.0). Note The initial state is not limited by this option. If you have a maximum number set and no columns hidden by class (`columnSelector-false` or by `columnSelector_columns` option, then all columns will be visible! The setting does not take into account the disabled columns (columns not listed in the column selector). So, in the first example below, the "Name" and "Major" columns are disabled (not included in the popup). If this option was set to `2`, only two additional columns, not counting the "Name" and "Major" columns can be made visible. Set this value to `null` to disable it. Default value: `null`
columnSelector_minVisible | Set this option to a number to set a minimum number of visible columns (v2.27.0). Note The initial state is not limited by this option. If you have all columns hidden initially, then all columns will be hidden! The setting does not take into account the disabled columns (columns not listed in the column selector). So, in the first example below, the "Name" and "Major" columns are disabled (not included in the popup). If this option was set to `1`, then one of the columns, not including the "Name" & "Major" columns, must always be visible. Set this value to `null` to disable it. Default value: `null`
columnSelector_breakpoints | This option defines the media query breakpoints with which to use when a column with the associated priority is hidden or revealed. For example, The last entry "70em" (1,120px) is assigned to data-priority 6. When the browser width is below this dimension, all columns with a data-priority of six will be hidden. Then when a browser width less than "60em" (960px) is reached, all columns of data-priority 5 and above will be hidden. At "50em" (800px), all columns of data-priority 4 and above are hidden, etc. Adjust these values as desired, but a maximum number data-priorities is set by the `columnSelector_maxPriorities` value (v2.25.9). Default value: `[ "20em", "30em", "40em", "50em", "60em", "70em" ]`
columnSelector_maxPriorities | This option sets the maximum number of priorities (v2.25.9). If for some reason you need to change the number of priorities (especially increase the number), then change this setting to reflect the maximum number of available priorities. Then make sure to modify the `columnSelector_breakpoints` to match this new value. Default value: `6`
columnSelector_priority | This is the assigned data-attribute which contains the defined data priority for a table column Values of 1 through 6 set the breakpoints of that particular column. A value of 1 has the highest priority, meaning it is the last column(s) to be hidden when the browser width goes below "20em" (320px). A value of 7 has the lowest priority, meaning it is the first column(s) to be hidden when the browser width goes below "70em" (1,120px). Any named priority value, (e.g. "critical" or "persistent") will flag the widget to remove that column from the selector list. Undefined priorities will default to a priority value of 1. Default value: `'data-priority'`
columnSelector_cssChecked | This class name is added to the input checkbox when it is checked This was added because we found an issue in the latest version of Chrome where the css selector `input:checked` was not correctly modifying the displayed Font Awesome replacement icon when the checkbox was toggled. Use `input.checked` (or whatever value setting this class name option contains to get around this issue). See this demo by TheSin which uses this option to change the checkbox style. Default value: `'checked'`
columnSelector_classHasSpan | Class name added to rows that have a span (e.g. grouping widget & other rows inside the tbody) (v2.29.0) This was added to allow customizing the css name in case of conflicts. The grouping widget accesses this value to ensure that group rows are not hidden when the first column is toggled. Default value: `'hasSpan'`
columnSelector_updated | This event is triggered after the columnSelector has completed updating (v2.23.2) Bind to this event if you to need to perform an action after the columnSelector has finished hiding or showing columns. Use it as follows
    $('table').on('columnUpdate', function() {
      // set ascending sort on first column
      $(this).trigger('sorton', [ [[0,0]] ]);
    });
Default value: `'columnUpdate'`

### Methods

Refresh the breakpoints and selected columns using this method (v2.17.0):

    $('table').trigger('refreshColumnSelector');

In v2.23.0, this method was expanded to allow the refreshing of the selector content & set auto and column modes.

- Here are a few examples:

  Method | Description
  `$('table').trigger('refreshColumnSelector');` | Refresh current settings; mainly used to update the css used to hide/show columns
  `$('table').trigger('refreshColumnSelector', [ [2,3,4] ]);` | Set visible columns; turn off "auto" mode (original method).
  `$('table').trigger('refreshColumnSelector', [ 'columns', [5,6] ]);` | Set visible columns; turn off "auto" mode (alternative method).
  `$('table').trigger('refreshColumnSelector', true);` | Turn on "auto" mode (original method).
  `$('table').trigger('refreshColumnSelector', [ 'auto', true ]);` | Turn on "auto" mode (alternate method).
  `$('table').trigger('refreshColumnSelector', [ 'auto', false ]);` | Turn off "auto" mode (alternate method).
  `$('table').trigger('refreshColumnSelector', [ 'auto', [2,3,4] ]);` | Turn on "auto" mode & set visible columns when "auto" is off.
  `$('table').trigger('refreshColumnSelector', 'selectors');` | Refresh selector popup contents & maintain "auto" mode; this allows updating column priorities, column names & widget options.
  `$('table').trigger('refreshColumnSelector', [ 'selectors', [5,6] ]);` | Refresh selector popup contents; Set visible columns & turn off "auto" mode.
  `$('table').trigger('refreshColumnSelector', [ 'selectors', true ]);` | Refresh selector popup contents; Turn on "auto" mode

  The function used for this method was also split out from the event handler, so if you want you can access it directly as follows:

      var config = $('table')[0].config;
      // example: refreshColumns( config, 'selectors', [5,6] );
      $.tablesorter.columnSelector.refreshColumns( config, optionName, optionState );

In v2.19.0, this method will now accept a parameter.

- The parameter can be either an array of zero-based column indexes to toggle columns on and off:

      $('table').trigger('refreshColumnSelector', [ [2,3,4] ]);

  Note
  - Passing an array will turn "auto" mode off.
  - Make sure to wrap the array inside another array.
  - Columns marked as "critical" or "disable" will never get toggled off using this method.

- Or, set the parameter to any non-array value to turn the "auto" mode on - this only works if the `columnSelector_mediaquery` is set to `true`:

      $('table').trigger('refreshColumnSelector', true);

### Removing a column from the selector

This is probably overkill, but there are numerous ways to remove a column from the selection popup (v2.15.6):

- Setting the `data-priority` to any non-numerical name (e.g. "critical" or "persistent").
- Setting the column selector widget columns option `columnSelector_columns : { 0 : 'disable' }`.
- The following methods, added to the header cell, in order of priority:
  - jQuery data `data-columnSelector="disable"`.
  - metadata `class="{ columnSelector : disable }"` (requires the metadata plugin).
  - headers option `headers : { 0 : { columnSelector: 'disable' } }`.
  - header class name `class="columnSelector-disable"`.

* *NOTE* Prior to v2.15.6, setting these methods to "false" would remove it from the selector. Now, they must be set to "disable" to remove the column from the selector, this was done to make it more consistent with the `columnSelector_columns` setting.

# Demo

### CSS only popup

Column
(When "Auto" is set, the table becomes responsive; resize the browser window to see it work)

Student | Courses
--- | ---
Name | Major | Sex | English | Japanese | Calculus | Geometry
Name | Major | Sex | English | Japanese | Calculus | Geometry
Student | Courses
Student03 | Languages | female | 85 | 95 | 80 | 85
Student04 | Languages | male | 60 | 55 | 100 | 100
Student05 | Languages | female | 68 | 80 | 95 | 80
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
Student01 | Languages | male | 80 | 70 | 75 | 80
Student02 | Mathematics | male | 90 | 88 | 100 | 90
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

### Bootstrap Popover

Rank | First Name | Last Name | Age | Total | Discount | Date
--- | --- | --- | --- | --- | --- | ---
1 | Philip Aaron Wong | Johnson Sr Esq | 25 | $5.95 | 22% | Jun 26, 2004 7:22 AM
11 | Aaron | Hibert | 12 | $2.99 | 5% | Aug 21, 2009 12:21 PM
12 | Brandon Clark | Henry Jr | 51 | $42.29 | 18% | Oct 13, 2000 1:15 PM
111 | Peter | Parker | 28 | $9.99 | 20% | Jul 6, 2006 8:14 AM
21 | John | Hood | 33 | $19.99 | 25% | Dec 10, 2002 5:14 AM
013 | Clark | Kent Sr. | 18 | $15.89 | 44% | Jan 12, 2003 11:14 AM
005 | Bruce | Almighty Esq | 45 | $153.19 | 44% | Jan 18, 2021 9:12 AM
10 | Alex | Dumass | 13 | $5.29 | 4% | Jan 8, 2012 5:11 PM
16 | Jim | Franco | 24 | $14.19 | 14% | Jan 14, 2004 11:23 AM
166 | Bruce Lee | Evans | 22 | $13.19 | 11% | Jan 18, 2007 9:12 AM
100 | Brenda Dexter | McMasters | 18 | $55.20 | 15% | Feb 12, 2010 7:23 PM
55 | Dennis | Bronson | 65 | $123.00 | 32% | Jan 20, 2001 1:12 PM
9 | Martha | delFuego | 25 | $22.09 | 17% | Jun 11, 2011 10:55 AM

# Css

# HTML

    <h3>CSS only popup</h3>
    <!-- This selector markup is completely customizable -->
    <div class="columnSelectorWrapper">
    	<input id="colSelect1" type="checkbox" class="hidden">
    	<label class="columnSelectorButton" for="colSelect1">Column</label>
    	<div id="columnSelector" class="columnSelector">
    		<!-- this div is where the column selector is added -->
    	</div>
    </div>

    <table class="tablesorter custom-popup">
    	<thead>
    		<tr class="tablesorter-ignoreRow"> <!-- Ignore all cell content; disable sorting & form interaction  -->
    			<th data-priority="critical">Name</th>
    			<!-- Remove column from selection popup by including -->
    			<!-- data-priority="Anything other than 1-6" OR data-column-selector="disable" OR  class="columnSelector-disable" -->
    			<th class="columnSelector-disable">Major</th>
    			<!-- columnSelector-false will initially hide the column -->
    			<th class="columnSelector-false" data-priority="6" data-selector-name="Gender">Sex</th>
    			<th data-priority="4">English</th>
    			<th data-priority="5">Japanese</th>
    			<th data-priority="3">Calculus</th>
    			<th data-priority="2">Geometry</th>
    		</tr>
    	</thead>
    	<tfoot>
    		<tr><th>Name</th><th>Major</th><th>Sex</th><th>English</th><th>Japanese</th><th>Calculus</th><th>Geometry</th></tr>
    	</tfoot>
    	<tbody>
    		<!-- ... -->
    	</tbody>
    </table>

    <h3>Bootstrap Popover</h3>
    <!-- Bootstrap popover button -->
    <button id="popover" type="button" class="btn btn-default">
    	Select Column
    </button>

    <div class="hidden">
    	<div id="popover-target"></div>
    </div>

    <table class="tablesorter bootstrap-popup">
    	<thead>
    		<tr>
    			<th data-priority="critical">Rank</th>
    			<th data-priority="3">First Name</th>
    			<th data-priority="critical">Last Name</th>
    			<th data-priority="4">Age</th>
    			<th data-priority="4">Total</th>
    			<th data-priority="5">Discount</th>
    			<th data-priority="6">Date</th>
    		</tr>
    	</thead>
    	<tbody>
    		<!-- ... -->
    	</tbody>
    </table>

# Javascript