# tablesorter

## Grouping Rows Widget

### Flexible client-side table sorting

Back to documentation

### Notes

- This widget will only work in tablesorter version 2.8+ and jQuery version 1.7+.
- Please do not use this widget in very large tables (it might be really slow) or when your table includes multiple tbodies.
- In v2.24.1
  - Added `"group-text"` group type to the Header Class Names. This class name will use the all of the text from the cell (this would essentially be the same as using "group-word-999").
  - Updated this demo to use the new "weekday-index" parser when the date column is set to "group-date-weekday", and to use the "time" parser when the date column is set to "group-date-time". It is not the most efficient because changing parsers requires an "update".
- In v2.24.0
  - This widget now works properly when used with a pager that has the `removeRows` option set to `true`.
  - Added `group_time24Hour` (set 12 vs 24 hour time) & `group_dateInvalid` (group header text) options.
  - Improved compatibility of the group widget with jQuery Globalize.
  - The `group_months` option will now accept a zero or one-based array or object of month names.
  - The `group_week` option will now accept an object using three-letter English weekday abbreviations as a key.
  - The `group_time` option will now accept an object using "am" or "pm" as a key.
  - For more detail, see the description column for the option in the Options section below.
  - For information on how to load & use Globalize, see the Globalization section below.

### Older Notes

- In v2.23.3
  - Added `group_forceColumn` & `group_enforceSort` options for force column grouping.
  - Updated method used to save collapsed groups, so any previously collapsed groups will be ignored after this update.
- In v2.22.0, group headers are now keyboard accessible using `Tab`; and pressing `Enter` while the header has focus will toggle the group header, or use `Shift` + `Enter` to toggle all groups.
- In v2.21.0
  - Added `group_checkbox` option to allow setting the parsed text from the "parser-input-select.js" checkbox parser.
  - Fixed an issue with the filter widget overriding the "group-hidden" class name.
- In v2.15.6, added `group_saveGroups` & `group_saveReset` options. More details are included in the "Options" section.
- In v2.14, added `group_dateString` option. More details are included in the "Options" section.
- In v2.13, added `group_separator` option & `group-separator-#` header class name. To see this in action, check out the file type parser demo.
- In v2.12, added `group_callback` & `group_complete` options. See options section below for details.
- In v2.11:
  - The grouping widget now works across multiple tbodies.
  - Added `group-false` header option which disables the grouping widget for a specific column.
  - Added the `group_collapsed` option - get more details in the options block below.
  - You can now toggle all group rows by holding down the `Shift` key while clicking on a group header.
  - This widget now works properly with the pager addon (pager addon updated).

- Clicking on any of the sortable header cells will cause the column below it to sort and add a group header.

### Options

#### Group 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
--- | --- | ---
group_collapsible | `true` | when `true`, the group headers become clickable and collapse the rows below it.
group_collapsed | `false` | when `true` and `group_collapsible` is also `true`, all groups will start collapsed (v2.11)
group_saveGroups | `true` | Remember collapsed groups (v2.15.6) This option saves the currently collapsed groups, using the group name. Collapsed groups are saved by column and group class name, so that the groups can be dynamically changed and still remember the correct collapsed groups. Try changing the group names (using the sliders) in the demo below & then collapsing some groups several times; go back to previous groups and it will remember which groups were collapsed. Because the group name is saved, groups with a number range (e.g. "group-number-10"; see the "Numeric" column below) will show a different range depending on sort direction; in this situation, each sort direction is saved independently. This option requires the `$.tablesorter.storage` utility contained within the `jquery.tablesorter.widgets.js` file.
group_saveReset | `null` | Element used to clear saved collapsed groups (v2.15.6) This option should contain a jQuery selector string or jQuery object pointing to an element to be used to reset (clear) the list of collapsed groups. You can also clear the saved collapsed groups by calling this function: `$.tablesorter.grouping.clearSavedGroups(table);` (table would be either the table DOM or table jQuery object). This option requires the `$.tablesorter.storage` utility contained within the `jquery.tablesorter.widgets.js` file.
group_count | `" ({num})"` | Allows you to add custom formatting, or remove, the group count within the group header. Set it to `false` or an empty string to remove the count. *NOTE* The value that replaces the `{num}` placeholder only counts the number of visible rows.
group_separator | `"-"` | When the `group-separator` class name is added, it uses the setting from this option to split the table cell content for grouping v2.13. If your content has mixed separators (e.g. `images/cats/burger-time.jpg`), you can set this option to use a regular expression:
    // the above example becomes: ["images", "cats", "burger-time", "jpg"]
    group_separator : /[/.]/
group_formatter | `null` | Use this function to modify the group header text before it gets applied. It provides various parameters (`txt, col, table, c, wo`) to make it work for any of the table columns and data. See the comments in the example below for more details. `txt` - current text of the group header. `col` - current table column being grouped (zero-based index). `table` - current table (DOM). `c` - table configuration data from `table.config`. `wo` - table widget options from `table.config.widgetOptions`. `data` - group & row data. This includes: `data.group` - (String) Current Group Name. Same as `txt`. `data.column` - (Number) Current column. Same as `col`. `data.$row` - (jQuery object) Row at the start of a group (group header is inserted before this row). `data.rowData` - (Array) Parsed data from `data.$row`; `data.rowData[ c.columns ]` contains raw row data & any associated child rows. `data.groupIndex` - (Number) Do not change - Current group header index. `data.groupClass` - (Array) Do not change - Class name applied to the header cell, e.g. `'group-letter-1'`. `data.grouping` - (Array) Do not change - This is the `data.groupClass` split into its components, e.g. `['group','letter','1']`. `data.savedGroup` - (Boolean) Do not change - Value is `true` if the group is collapsed & saved to storage. `data.currentGroup` - (String) Do not use This value is immediately replaced by the `group_formatter` returned value.
    group_formatter : function(txt, col, table, c, wo, data) {
      // If there are empty cells, name the group "Empty"
      return txt === "" ? "Empty" : txt;
    }
group_callback | `null` | Use this function to further modify the group header to include more information (i.e. group totals). Parameters include (`$cell, $rows, column, table`). See the example below for more details v2.12. `$cell` - current group header table cell (jQuery object). `$rows` - current group rows (jQuery object). `column` - current table column being grouped (zero-based index). `table` - current table (DOM).
    group_callback : function($cell, $rows, column, table){
      $cell.find('.group-name').append(' group'); // adds "group" to the end of the group name
    }
group_complete | `"groupingComplete"` | Event triggered on the table when the grouping widget has finished work v2.12.
    $('table').on('groupingComplete', function(){
      // always hide empty groups ("Empty" can be added by the group_formatter function)
      $(this).find('.group-header:contains("Empty")').trigger('toggleGroup');
    });
group_forceColumn | `[]` | Force the group widget to only apply to one column (v2.23.3). When this option is set, only the first value in the array is used; it is set up as an array for future expansion. When set, the set column will be the only column grouped by this widget. If the `group_enforceSort` option is set to `false`, the column will be grouped without a sort applied to the table.
group_enforceSort | `true` | Only allow `group_forceColumn` to work when a sort is applied to the table (v2.23.3).
group_checkbox | (see description) | Set checkbox parser text (v2.21.0) The checkbox parser in the "parser-input-select.js" file will use this option to set the group header text displayed for a checkbox state. Defaults are: `[ "checked", "unchecked" ]`
group_months | (see description) | Name arrays included so that the language of the date groups can be modified easily (v2.24.0; see "Globalization" section for details). Showing defaults (English):
    // zero-based array
    group_months: [ "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" ]
As of v2.24.0, this option will also work with an object with a one-base "index":
    // get Months list from CLDR (see Globalization section for more info)
    var months = new Cldr( 'en' ).main([ "dates/calendars/gregorian/months", "format", "abbreviated" ]);
    // one-based object (CLDR output example)
    // months = { 1: "Jan", 2: "Feb", 3: "Mar", 4: "Apr", 5: "May", 6: "Jun", 7: "Jul", 8: "Aug", 9: "Sep", 10: "Oct", 11: "Nov", 12: "Dec" }
    // then in the widgetOptions,
    group_months: months
A one-based array of month names will also work.
    group_months: [ "", "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" ]
group_week | (see description) | Name arrays included so that the language of the date groups can be modified easily (v2.24.0; see "Globalization" for details). Showing defaults (English):
    // zero-based index
    group_week: [ "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday" ]
As of v2.24.0, this option will also work with an object using a three-letter English weekday abbreviated names as a key:
    // get weekdays list from CLDR (see Globalization section for more info)
    var weekdays = new Cldr( 'en' ).main([ "dates/calendars/gregorian/days", "format", "abbreviated" ]);
    // week-abbreviation based object
    // weekdays = { sun: "Sun", mon: "Mon", tue: "Tue", wed: "Wed", thu: "Thu", fri: "Fri", sat: "Sat" }
    // then in the widgetOptions,
    group_week: weekdays
At this point, if you're going to use Globalization, it would be best to use the `group_dateString` to use `globalize.dateFormatter` to format the date because not all locales start their week on Sunday.
group_time | (see description) | Name arrays included so that the language of the date groups can be modified easily (v2.24.0; see "Globalization" for details). Defaults (English):
    group_time: [ "AM", "PM" ]
As of v2.24.0, this option will also work with an object in this format:
    // get time of day list from CLDR (see Globalization section for more info)
    var periods = cldr.main([ "dates/calendars/gregorian/dayPeriods", "format", "abbreviated" ]);
    /* time of day: CLDR returns this object:
    peroids = {
    	afternoon1: "in the afternoon",
    	am: "AM",
    	am-alt-variant: "am",
    	evening1: "in the evening",
    	midnight: "midnight",
    	morning1: "in the morning",
    	night1: "at night",
    	noon: "noon",
    	pm: "PM",
    	pm-alt-variant: "pm"
    }
    then in the widgetOptions,*/
    group_time: periods
If you want to use a time of day other than "am" or "pm", then you'll need to use the `group_dateString` to format the date; see the example in the Globalization section below.
group_time24Hour | `false` | Set to `true` to display time in 24 hour format (v2.24.0).
group_dateInvalid | `'Invalid Date'` | Message added to the Group header if a date is invalid (v2.24.0).
group_dateString | (see description) | When the `"group-date"` class name is set on a column, this function is used to format the date string (v2.24.0). This is the default function:
    // you can just return date, date.toLocaleString(), date.toLocaleDateString() or d.toLocaleTimeString()
    group_dateString : function(date, config, $header ) {
      return date.toLocaleString();
    }
Other functions that can be used are `date` (alone), `date.toLocaleString()`, `date.toLocaleDateString()` or `d.toLocaleTimeString()`. See this reference for more details. In v2.24.0, this widget was updated to make it easier to use with jQuery Globalize. Additionally, two new parameters were added: `config` and `$header` (a jQuery object of the associated header cell).

### Header Class Names

#### Group header class names (when changing the grouping, notice that the sort doesn't change, just the position and names of the group headers):

Group type | Group class name | Description
--- | --- | ---
Disable | `"group-false"` | Disable grouping of rows for a column (v2.11).
Text | `"group-text"` | Group the rows using all of the text from the column's parsed data.
`"group-word"` | Group the rows using the first word it finds in the column's parsed data (same as `"group-word-1"`).
`"group-word-n"`* | Group the rows using the nth word in the column (`"n"` can be any number).
`"group-letter"` | Group the rows using the first letter it finds in the column's parsed data (same as `"group-letter-1"`).
`"group-letter-n"`* | Group the rows using letters 1 through n (if n = 2, then it's the first 2 letters) in the column's parsed data (`"n"` can be any number).
Number | `"group-number"` | Group the rows by the number it finds in the column (step of one; same as `"group-number-1"`).
`"group-number-n"`* | Group the rows into blocks of every n values. So, if n = 10, the groups will be 0-9, 10-19, 20-29, etc (`"n"` can be any number).
Separator | `"group-separator"` | Group the rows using the text between the start and first separator that it finds in the column's parsed data (same as `"group-separator-1"`) (v2.13).
`"group-separator-n"`* | Group the rows using the nth separated group in the column (`"n"` can be any number) (v2.13).
Date | `"group-date"` | Group the rows by full date (this shows the current UTC time corrected for your time zone).
`"group-date-year"`* | Group the rows by year.
`"group-date-month"`* | Group the rows by month.
`"group-date-monthyear"`* | Group the rows by month & year.
`"group-date-week"`* | Group the rows by day of the week.
`"group-date-day"`* | Group the rows by month/day.
`"group-date-time"`* | Group the rows by time.

* When sorting some columns, different group headers with the same group name may exist. To make these columns sort specifically by the group you want, you'll need to modify the parser.

Before v2.24.1, this demo only used the "shortDate" parser on the date column, so when "group-date-week" or "group-date-time" were set, group headers would repeat.

### Globalization

### jQuery Globalize

These instructions are specific to jQuery Globalize.

Here is a demo showing how all the code comes together; there is no official site with JSON files available to load into the demo, so only the required snippets of CLDR data are included in the demo.

#### Make sure to include files from:

- jQuery Globalize:
  - Process CLDR data into usable formats.
  - Install from npm (`npm install globalize cldr-data`), bower (`bower install globalize`), or
  - Download from https://github.com/jquery/globalize.
  - Depending on the data in your table, you'll need to pick which modules to include; currently for the date module, you'll need to load the number module first (ref).
  - Here is an example of how to load all files from Cdnjs (make sure to use the most recent version):

        <script src="https://cdnjs.cloudflare.com/ajax/libs/globalize/1.0.0/globalize.min.js"></script>
        <script src="https://cdnjs.cloudflare.com/ajax/libs/globalize/1.0.0/globalize/currency.min.js"></script>
        <script src="https://cdnjs.cloudflare.com/ajax/libs/globalize/1.0.0/globalize/number.min.js"></script>
        <script src="https://cdnjs.cloudflare.com/ajax/libs/globalize/1.0.0/globalize/date.min.js"></script>
        <script src="https://cdnjs.cloudflare.com/ajax/libs/globalize/1.0.0/globalize/message.min.js"></script>
        <script src="https://cdnjs.cloudflare.com/ajax/libs/globalize/1.0.0/globalize/plural.min.js"></script>
        <script src="https://cdnjs.cloudflare.com/ajax/libs/globalize/1.0.0/globalize/relative-time.min.js"></script>

- cldrjs:
  - Needed by Globalize to traverse CLDR data.
  - Install from npm (`npm install cldrjs`), bower (`bower install cldrjs`), or
  - Download from https://github.com/rxaviers/cldrjs.
  - You will likely need to include all files: `cldr.js`, `event.js`, `supplemental.js` and `unresolved.js`.
  - Here is an example of how to load all files from Cdnjs (make sure to use the most recent version):

        <script src="https://cdnjs.cloudflare.com/ajax/libs/cldrjs/0.4.3/cldr.min.js"></script>
        <script src="https://cdnjs.cloudflare.com/ajax/libs/cldrjs/0.4.3/cldr/event.min.js"></script>
        <script src="https://cdnjs.cloudflare.com/ajax/libs/cldrjs/0.4.3/cldr/supplemental.min.js"></script>
        <script src="https://cdnjs.cloudflare.com/ajax/libs/cldrjs/0.4.3/cldr/unresolved.min.js"></script>

- CLDR data:
  - Needed by Globalize & cldrjs.
  - Install from npm (`npm install cldr-data`), bower (`bower install cldr-data`), or
  - Find the latest version from here: http://cldr.unicode.org/index/downloads
  - And download the files from here: http://unicode.org/Public/cldr/ (it is really hard to find this page).
  - For more information on which json files you'll need to include, check out these instructions.

#### Initialization

The next step is loading the CLDR data into Globalize; please see this page for more details.

    // code to show how to load a language using jQuery (make sure it was loaded)
    $(function() {
    	var hasInitialized = false,
    		loadLanguage = function( lang ) {
    			// Use $.getJSON instead of $.get if your server is not configured to return the
    			// right MIME type for .json files.
    			var files = [];
    			if ( !hasInitialized ) {
    				files = [
    					/* core */
    					$.getJSON( 'cldr-data/supplemental/likelySubtags.json' ),
    					/* currency */
    					$.getJSON( 'cldr-data/supplemental/currencyData.json' ),
    					/* date */
    					$.getJSON( 'cldr-data/supplemental/timeData.json' ),
    					$.getJSON( 'cldr-data/supplemental/weekData.json' ),
    					/* number */
    					$.getJSON( 'cldr-data/supplemental/numberingSystems.json' ),
    					/* plural */
    					$.getJSON( 'cldr-data/supplemental/plurals.json' ),
    					$.getJSON( 'cldr-data/supplemental/ordinals.json' )
    				];
    			}
    			files = files.concat([
    				/* currency */
    				$.getJSON( 'cldr-data/main/' + lang + '/currencies.json' ),
    				/* date */
    				$.getJSON( 'cldr-data/main/' + lang + '/ca-gregorian.json' ),
    				$.getJSON( 'cldr-data/main/' + lang + '/timeZoneNames.json' ),
    				/* number */
    				$.getJSON( 'cldr-data/main/' + lang + '/numbers.json' ),
    				/* relative time */
    				$.getJSON( 'cldr-data/main/' + lang + '/dateFields.json' ),
    				/* unit */
    				$.getJSON( 'cldr-data/main/' + lang + '/units.json' )
    			]);
    			$.when
    				.apply( $, files )
    				.then( function() {
    					// Normalize $.get results, we only need the JSON, not the request statuses.
    					return [].slice.apply( arguments, [ 0 ] ).map( function( result ) {
    						return result[ 0 ];
    					});
    				})
    				.then( Globalize.load )
    				.then( function() {
    					if ( !hasInitialized ) {
    						// initialization code goes here
    					}
    					hasInitialized = true;
    					// code to run after each new language has loaded goes here
    				});
    		};

    	// initial language load
    	loadLanguage( 'en' );
    });

#### Usage

Use Globalize with tablesorter & the group widget inside of the `group_dateString` callback function.

In v2.24.0

- The `group_months`, `group_week` & `group_time` options were modified to work with CLDR data.
- `group_months` option will work with either a zero-based array of month names (basic use), or an object with a key using a one-based indexed with a month name value pair (the CLDR format; see the "months" comment in code example below).
- `group_week` option will work with either a zero-based array of weekday names (basic use), or an object with a key using three letter abbreviations of English weekday names with a localized weekday name value pair (the CLDR format; see the "days of week" comment in the code below).
- `group_time` option will now accept an object using "am" or "pm" (both lower case) as a key.
- The `group_dateString` callback function was updated with two additional parameters to allow access to table data. See the "Options" section above for more details.
- Check out this demo using the code below

    $( function() {
    	// using an english example
    	var lang = 'en',
    		cldr = new Cldr( lang ),
    		// Globalize.load already done!!
    		globalize = Globalize.locale( lang ),
    		// months: CLDR returns an object { 1: "Jan", 2: "Feb", 3: "Mar", ..., 12: "Dec" }
    		months = cldr.main([ "dates/calendars/gregorian/months", "format", "abbreviated" ]),
    		// days of week: CLDR returns { sun: "Sun", mon: "Mon", tue: "Tue", wed: "Wed", thu: "Thu", ... }
    		week = cldr.main([ "dates/calendars/gregorian/days", "format", "abbreviated" ]),
    		/* time of day: CLDR returns
    			{ afternoon1: "in the afternoon", am: "AM", am-alt-variant: "am", evening1: "in the evening", midnight: "midnight",
    			  morning1: "in the morning", night1: "at night", noon: "noon", pm: "PM", pm-alt-variant: "pm" } */
    		periods = cldr.main([ "dates/calendars/gregorian/dayPeriods", "format", "abbreviated" ]);

    	$( 'table' ).tablesorter({
    		theme : 'blue',
    		widgets: [ 'group', 'zebra' ],
    		widgetOptions : {
    			group_months     : months,
    			group_week       : week,
    			// setting group_times to an empty string forces "group-time" to use group_dateString function
    			group_time       : periods,
    			group_dateString : function ( date, c, $column ) {
    				// see https://github.com/jquery/globalize/blob/master/doc/api/date/date-formatter.md
    				var hour = date.getHours(),
    					min = date.getMinutes(),
    					format = globalize.dateFormatter({ datetime: "full" })( date ),
    					time = globalize.dateFormatter({ time: "full" })( date );
    				// replace special times with time period
    				if ( hour === 0 && min === 0 ) {
    					// midnight: this method may not work in all locales!
    					return format.replace( time, periods.midnight );
    				} else if ( hour === 12 && min === 0 ) {
    					// noon: this method may not work in all locales!
    					return format.replace( time, periods.noon );
    				}
    				return format;
    			}
    		}
    	});

    });

# Demo

Numeric column:
(includes subtotals)
Animals column:
Date column:
†

| Quality (number) | Numeric (every 10) | Priority (letter) | Animals (first letter) | Natural Sort (first word) | Inputs (second word) | Date (Full)
--- | --- | --- | --- | --- | --- | --- | ---
| Quality | Numeric | Priority | Animals | Natural Sort | Inputs | Date
| 1 | 10 |  | Koala | abc 123 |  | 1/13/2013 12:01 AM
| 3 | 29 |  | Kangaroo | abc 1 |  | 1/15/2013
| 2 | 10 |  | Ant | abc 9 |  | 1/13/2013
| 3 | 81 |  | Bee | zyx 24 |  | 1/11/2013
| 3 | 21 |  | Aardwolf | zyx 55 |  | 1/13/2013 03:30 AM
| 1 | 3 |  | Bear | abc 11 |  | 1/15/2013
| 4 | 12 |  | Armadillo | zyx 2 |  | 1/15/2013 12:30 PM
| 2 | 56 |  | Aardvark | abc 2 |  | 1/22/2013
| 1 | 55 |  | Lion | abc 9 |  | 2/15/2013
| 4 | 87 |  | Anteater | ABC 10 |  | 1/3/2013
| 2 | 98 |  | Lemur | zyx 1 |  | 1/11/2013
| 1 | 20 |  | Llama | zyx 12 |  | 12/13/2012

† When "group-date-week" is set, the parser is changed to "weekday-index". And when "group-date-time" is set, the "time" parser is being used. All other date column settings use the "shortDate" parser.

# Page Header

    <!-- Tablesorter: required -->
    <link href="../css/theme.blue.css" rel="stylesheet">
    <script src="../js/jquery.tablesorter.js"></script>
    <script src="../js/jquery.tablesorter.widgets.js"></script>

    <!-- Grouping widget -->
    <script src="../js/parsers/parser-input-select.js"></script>
    <script src="../js/widgets/widget-grouping.js"></script>

# Script

# CSS

# HTML