Notes

  • To bind events to the newly created table, see the Adding event bindings section below.
  • Build a table starting with an assortment of data types ( array, text (CSV, HTML) or object (json) ).
  • This widget isn't really a widget because it is run and does it's processing before tablesorter has initialized; but the options for it are contained within the tablesorter widgetOptions.
  • Using the core build options:
    • The build_type tells the widget which type of data processing to use on the data.
    • The build_source points the widget to the data source.
    • Once the data is obtained from the build_source, you can do whatever processing that needs to be done on it using the build_processing option.
      • For example, if the table data is within a larger JSON, you can just return that portion of the JSON to the widget: build_processing : function(data, wo) { return data.all_info_tables.table_of_contents; }
      • Anoter example is to use the processing option to split a string into an array (see the "Array (from string w/processing)" section below)
  • An extra option named build_numbers has been included:
    • This option only applies to array and csv source table builds.
    • Set the build_numbers.addColumn option to true (or a string with the column name "#") to add a row number column on the far left of the table.
    • Set the build_numbers.sortable option to true to make the added number column sortable. This option only applies if the addColumn option is true.

Adding event bindings

Internally, all triggered events use jQuery's triggerHandler method to get around the issue of events triggered on a nested table bubbling up to the parent table; e.g. we don't want a "sortEnd" event to trigger on a parent table when a nested table has completed sorting.

A binding added to the wrapper will not execute, and you can not target a table element that has not yet been created.

To add an event listener to a table created by the build widget, you will need to use the initialized callback:

HTML (before)
<!-- empty wrapper before the table has been built -->
<div id="wrapper"></div>
Javascript
$(function() {
  $('#wrapper').tablesorter({
    theme: 'blue',
    widgets: ['zebra'],
    data : dataObject,
    initialized: function(table) {
      $(table).on('sortStart', function() {
        alert('ok');
      });
    }
  });
});
HTML (after)
<div id="wrapper">
  <table class="tablesorter-blue">
    <!-- ... -->
  </table>
</div>

Options

widgetOption Type Default Description
Core Options
String "" Indicate the data result type that needs to be processed

Options include: "array", "csv", "object", "json" or "html".
Default is "" (an empty string).
String "" Contains the data stored as an array, object, jQuery object or ajax settings used to obtain ajax data (include any desired ajax options).

Options include: an array, object, jQuery Object ($('.csv')) or ajax settings( { url: 'mysite.com/data.json', dataType: 'json' } ).
Function null Add a function that returns a useable build_type. (e.g. string to array)

The function receives two parameters: data which contains the obtained data and wo which is the widget options (table.config.widgetOptions).
Example: build_processing: function(data, wo) { return data.split(';'); }
build_complete String "tablesorter-build-complete" Contains the name of the event to trigger when a table build has completed.
CSV & Array Options
build_headers.rows Numeric 1 Number of header rows contained within the csv
build_headers.classes Array [] Array of header class names to add while building the table header.
Array [] Array of header cell names to add while building the table header.

Any value contained within this option will override any header text obtained from the CSV data.
build_headers.widths Array [] Array of header cell widths which are added to a <col> within a <colgroup>.
build_footers.rows Numeric 1 Number of footer rows contained within the csv
build_footers.classes Array [] Array of footer class names to add while building the table footer.
Array [] Array of footer cell names to add while building the table footer.

Any value contained within this option will override any footer text obtained from the CSV data.
Boolean false Include a row numbering column.

Only works with csv or array data.
Boolean false Make the included row number column sortable.

Only works when the build_numbers.addColumn is true and when csv or array data is used.
CSV Only Options
build_csvStartLine Numeric 0 The line within the csv data to start building the table
build_csvSeparator String "," (comma) The separator used within the text file (comma or tab)
Object Only Options
build_objectRowKey String "rows" Object key which contains row data
build_objectCellKey String "cells" Object key which contains the table cells, within the row data
build_objectHeaderKey String "headers" Object key which contains the table headers data
build_objectFooterKey String "footers" Object key which contains the table footers data

Setup - Common (document head)

Add the following required scripts and css files into the document <head>
<!-- jQuery -->
<script src="js/jquery-latest.min.js"></script>

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

<!-- build table widget -->
<script type="text/javascript" src="../js/widgets/widget-build-table.js"></script>

Setup - Array (javascript variable)

Notes

  • The array is set up such that it is an array of arrays. The outer array contains each row array, and within each row array is the cell text.
  • Using an array is limiting, so addtional options have been added:
    • (build_headers & build_footers) have been added allowing customizing the headers and/or footers.
    • The rows option sets the number of headers rows to include from the data source. Zero is not an option since tablesorter requires a thead in place before it will initialize.
    • The classes array sets each header cell (th) class name.
    • The text array within these options will override any text obtained from the data source.
    • The widths array, only in the build_headers option, sets column widths by building <col> elements within a <colgroup.
    • Adding class names to the tbody rows or cells isn't easily accomplished, but you can bind to the build complete event ('tablesorter-build-complete') and add them yourself.

HTML

<div id="array2Table"></div>

Javascript

$(function() {
	var arry = [
		[ 'ID', 'Name', 'Age', 'Date' ], // header
		[ 'A42b', 'Parker', 28, 'Jul 6, 2006 8:14 AM' ],  // row 1
		[ 'A255', 'Hood', 33, 'Dec 10, 2002 5:14 AM' ],   // row 2
		[ 'A33', 'Kent', 18, 'Jan 12, 2003 11:14 AM' ],   // row 3
		[ 'A1', 'Franklin', 45, 'Jan 18, 2001 9:12 AM' ], // row 4
		[ 'A102', 'Evans', 22, 'Jan 18, 2007 9:12 AM' ],  // row 5
		[ 'A42a', 'Everet', 22, 'Jan 18, 2007 9:12 AM' ], // row 6
		[ 'ID', 'Name', 'Age', 'Date' ]  // footer
	];

	$('#array2Table').tablesorter({
		theme: 'blue',
		widgets: ['zebra'],
		widgetOptions : {
			// build_type   : 'array', // can sometimes be detected if undefined
			build_source : arry,
			build_headers : {
				rows    : 1,  // Number of header rows from the csv
				classes : [], // Header classes to apply to cells
				text    : [], // Header cell text
				widths  : [ '15%', '30%', '15%', '40%' ] // set header cell widths
			},
			build_footers : {
				rows    : 1,   // Number of header rows from the csv
				classes : [],  // Footer classes to apply to cells
				text    : [ 'ID (a###)', 'Last Name', 'Age (joined)', 'Date (joined)' ] // Footer cell text
			}
		}
	});
});

Result

Setup - Array (from string w/processing)

Notes

  • We start out with a string and split it into a useable array of arrays.
  • The settings are similair to the Array (javascript variable) code above with the exception of using the build_processing function to create the array.
    • The string is set up to separate each row by a semi-colon, then each cell by a comma.
    • The first split is needed to create an array of rows .split(';')
    • The second split can be accomplished using .split(',') on each row of the array, but instead we use the build table widget function $.tablesorter.buildTable.splitCSV(cells, ','); to ensure that the split doesn't occur if the separator is within double quotes (note the footer text).
    • Then just return this newly built array back to the build table widget (see the full code below).

HTML

<div id="string2Table"></div>

Javascript

$(function() {
	$('#string2Table').tablesorter({
		theme: 'blue',
		widgets: ['zebra'],
		widgetOptions: {
			build_type   : 'array',
			build_source : 'header 1,header 2,header 3;r1c1,r1c2,r1c3;r2c1,r2c2,r2c3;r3c1,r3c2,r3c3;"footer, 1","footer, 2","footer, 3"',
			build_processing : function(data, wo) {
				var rows = data.split(';');
				return $.each(rows, function(i,cells) {
					// similar to using rows[i] = cells.split(',') but the splitCSV script
					// doesn't split the cell if the separator (comma) is within double quotes
					rows[i] = $.tablesorter.buildTable.splitCSV(cells, ',');
				});
			}
		}
	});
});

Result

Setup - CSV (txt within DOM element)

Notes

  • A jQuery object targeting the CSV text can be passed to the build_source option.
  • The widget detects that a jQuery object was passed to it, and grabs the HTML (not text) of the element.
    • Make sure not include HTML tags, or at least use the build_processing function to reformat the data.
    • The row of csv data is trimmed of extra tabs and spaces (only from the beginning & end of each row).
    • Building a table from CSV or array use the same script, so the same addtional options are available:
      • (build_headers & build_footers) have been added allowing customizing the headers and/or footers.
      • The rows option sets the number of headers rows to include from the data source. Zero is not an option since tablesorter requires a thead in place before it will initialize.
      • The classes array sets each header cell (th) class name.
      • The text array within these options will override any text obtained from the data source.
      • The widths array, only in the build_headers option, sets column widths by building <col> elements within a <colgroup.
      • Adding class names to the tbody rows or cells isn't easily accomplished, but you can bind to the build complete event ('tablesorter-build-complete') and add them yourself.
    • CSV data has two additional options used during data processing:
      • build_csvStartLine (default is 0) tells the csv build script which line in the csv data to start using to build the table. This is added in case comments or other data is above the table data.
      • build_csvSeparator (default is ",")
    • In this demo, the build_numbers sub-options addColumn and sortable are set to add a numeric column on the left side.
      • The addColumn option contains the name of the numeric column to be added to the header. Otherwise, set this option to false to not build this numeric column.
      • The sortable option makes that numeric column sortable.

HTML

<!--
 Note: if the csv data contains commas ("10,000 days") wrap it in quotes
-->
<div class="csv" style="display:none;">
	Album,Artist,Price (USD)
	Lateralus,Tool,$13.00
	Aenima,Tool,$12.00
	"10,000 days",Tool,$14.00
	Down In It,Nine Inch Nails,$3.00
	Broken,Nine Inch Nails,$6.00
	Muse,Black Holes and Revelations,$7.00
	Anon,"fake album, with comma", $1.00
	Album,Artist,Price (USD)
</div>

<div id="csv2Table"></div>

Javascript

$(function() {
	$('#csv2Table').tablesorter({
		theme: 'blue',
		widgets: ['zebra'],
		widgetOptions: {
			// *** build widget core ***
			build_type      : 'csv',
			build_source    : $('.csv'),
			build_complete  : 'tablesorter-build-complete', // triggered event when build completes

			// *** CSV & array ***
			build_headers   : {
				rows    : 1,   // Number of header rows from the csv
				classes : [],  // Header classes to apply to cells
				text    : [],  // Header cell text
				widths  : ['3%', '27%', '50%', '20%'] // set header cell widths
			},
			build_footers : {
				rows    : 1,   // Number of header rows from the csv
				classes : [],  // Footer classes to apply to cells
				text    : []   // Footer cell text
			},
			build_numbers : {
				addColumn : "#", // include row numbering column?
				sortable  : true // make column sortable?
			},

			// *** CSV options ***
			build_csvStartLine : 0,  // line within the csv to start adding to table
			build_csvSeparator : "," // csv separator
		}
	});
});

Result

Setup - CSV (txt file via ajax)

Notes

  • If the csv data is obtained via ajax instead of from a DOM element, only the build_source option needs to change, everything else stays the same.
    • Set the build_source to contain any ajax settings required to load the data.
    • In this case the csv file is contained within a text file (build.txt), so a url option is set to point to the file and the dataType option (set to html) is set so that ajax knows the type of file to access.
    • The remaining default settings were left out of the example below.
  • Please note that browsers like Chrome will not allow you to access locally hosted (desktop) files. Test it with Firefox instead.

Build.txt file

Album,Artist,Price ($)
Lateralus,Tool,$13.00
Aenima,Tool,$12.00
"10,000 days",Tool,$14.00
Down In It,Nine Inch Nails,$3.00
Broken,Nine Inch Nails,$6.00
Muse,Black Holes and Revelations,$7.00
Anon,"fake album, with comma", $1.00
Album,Artist,Price ($)

HTML

<div id="csv2Table2"></div>

Javascript

$(function() {
	$('#csv2Table2').tablesorter({
		theme: 'blue',
		widgets: ['zebra'],
		widgetOptions: {
			// *** build widget core ***
			build_type      : 'csv',
			build_source    : { url: 'assets/csv.txt', dataType: 'text' },
			build_headers   : {
				widths  : ['30%', '50%', '20%'] // set header cell widths
			}
		}
	});
});

Result

Setup - Object (javascript variable)

Notes

Definitions - General:

These are definitions to words as used within this documentation.
  • A key-value pair (or attribute): Within an object, the way to assign a value is by using a key-value pair ("name" : "Fred"; which is like saying name = "Fred" or x = 1 outside of an object).
  • A block is essentially the "value" portion of a key-value pair; specifically when referring to the value of the header, footer, row and cell blocks.
  • An array is a list or group of values (i.e. ['x','y','z']).
  • An array of arrays is an array that contains more arrays (i.e. [ ['a','b','c'], ['d','e','f' ] ]). This applies to the header, row and footer blocks.
  • Any build table widget object:
    • These objects are a grouping of key-value pairs used to define a tbody, row or cell.
    • These objects contains all of the attributes which are to be added to a table element while building the table.
    • The keys used in these attributes will look familiar - class (see row 7 below), colspan (see row 4 below), data-attributes (see row 7 cell 3 below), etc.
    • Depending on where an object is located (tbody, row or cell), it will have a special key word or words which are significant (see the Objects section below).

Blocks:

(row #), or (row # cell #) in these descriptions refer to the demo object code below
  • header block:
    • This block will contain an array of rows. The rows can be defined as another array of cell text (row 1-3,5-6), or row objects (row 0, 4 & 7).
    • The header object key name can be modified by changing the widget build_objectHeaderKey option.
  • footers block:
    • This block can contain all of the same data as the header block.
    • This block has one additional setting, it can also contain a very specific string: "clone". When this setting is used, the footer will be created by making a clone of the header.
    • The footers object key name can be modified by changing the widget build_objectFooterKey option.
  • rows block:
    • This block will contain an array of rows. The rows can be defined as another array of cell text, or as a row object (same as the header & footer blocks).
    • In addition, this block can contain a tbody object (tbody 2 & tbody 3; see the tbody object section below for more details).
    • The rows object key name can be modified by changing the widget build_objectRowKey option.
  • cells block:
    • This block will contain an array of cells. The cells can be defined as cell text (string), or cell objects.
    • The cells object key name can be modified by changing the widget build_objectCellKey option.

Object Content

  • tbody object
    • The tbody object contains all of the attributes that are to be applied to a particular table tbody (tbody).
    • The tbody object requires a newTbody key set to true. It is the ONLY way the build widget can differeniate a row object from a "new" tbody object.
    • If the newTbody attribute is true, the build widget will place all remaining rows into a new tbody; or all rows, until it encounters another valid tbody object, into a new tbody.
    • If the newTbody attribute is false, the build widget will assume the object is for a row and add it as a row.
    • See "TBODY 2" and "TBODY 3" tbody objects in the code example below.
  • row object
    • The row object contains all of the attributes that are to be applied to a particular table row (tr).
    • The row object requires a cells attribute.
    • The cells attribute will contain all table cell data for the cells within that table row.
    • This attribute can be changed by modifying the build table widget's build_objectCellKey (default is "cells").
    • See row 4 and row 7 in the demo code below.
  • row array
    • A row array can contain either the text for a table cell (row 0 cell 2 & 4), or a cell object (row 0 cell 1,3,5,6) contains.
    • It can also contain all cell text (row 1-3,5-6) or all cell objects (almost row 7) for cells within that row.
    • This method does not allow adding any row (tr) attributes, (i.e. class or data-attributes).
  • cell object
    • The cell object contains all of the attributes that are to be applied to a particular table cell (th (thead or tfoot) or td (tbody).
    • This object requires either a text (row 0 & row 7) or html (row 4) attribute to add content into the cell.
    • Within the first header row only, if a width attribute is defined, it will be applied to a <col> element and placed within a <colgroup> before the header.
    • See row 0 (header), row 4 and row 7 (rows) in the demo code below.
  • cell text
    • Within a row array or object, only the cell text can be included (row 0 cell 2,4; row 1-3,5-6; row 7 cell 5).
    • Within the header only, whenever cell content is added as a string, the widget will check the widgetOptions.build_headers.classes & wo.build_headers.widths (first row only) and apply any values it finds for that column to those cells.

HTML

<div id="object2Table"></div>

Javascript

$(function() {
	// object or JSON
	var dataObject = {
		headers : [
			[
				// each object/string is a cell
				{ text: 'First Name', class: 'fname', width: '10%' }, // row 0 cell 1
				'Last Name',                                          // row 0 cell 2
				{ text: 'Age', class: 'age', 'data-sorter' : false }, // row 0 cell 3
				'Total',                                              // row 0 cell 4
				{ text: 'Discount', class : 'sorter-false' },         // row 0 cell 5
				{ text: 'Date', class : 'date' }                      // row 0 cell 6
			]
		],
		footers : 'clone', // clone headers or assign array like headers
		rows : [
			// TBODY 1
			[ 'Peter', 'Parker',   28, '$9.99',   '20%', 'Jul 6, 2006 8:14 AM'   ], // row 1
			[ 'John',  'Hood',     33, '$19.99',  '25%', 'Dec 10, 2002 5:14 AM'  ], // row 2
			[ 'Clark', 'Kent',     18, '$15.89',  '44%', 'Jan 12, 2003 11:14 AM' ], // row 3

			// TBODY 2
			{ newTbody: true, class: 'tablesorter-infoOnly' },
			{ cells : [ { html: 'Info Row', colSpan: 6 } ] },      // row 4

			// TBODY 3
			{ newTbody: true },
			[ 'Bruce', 'Evans',    22, '$13.19',  '11%', 'Jan 18, 2007 9:12 AM'  ], // row 5
			[ 'Bruce', 'Almighty', 45, '$153.19', '44%', 'Jan 18, 2001 9:12 AM'  ], // row 6

			{ class: 'specialRow',                                                  // row 7
				cells: [
					// each object/string is a cell
					{ text: 'Fred', class: 'fname' },                                   // row 7 cell 1
					{ text: 'Smith', class: 'lname' },                                  // row 7 cell 2
					{ text: 18, class: 'age', 'data-info': "fake ID!, he's only 16" },  // row 7 cell 3
					{ text: '$22.44', class: 'total' },                                 // row 7 cell 4
					'8%',                                                               // row 7 cell 5
					{ text: 'Aug 20, 2012 10:15 AM', class: 'date' }                    // row 7 cell 6
				],
				'data-info' : 'This row likes turtles'
			}
		]
	};

	$('#object2Table').tablesorter({
		theme: 'blue',
		widgets: ['zebra'],
		data : dataObject, // same as using build_source (build_source would override this)
		widgetOptions : {
			// *** build object options ***
			build_objectRowKey    : 'rows',    // object key containing table rows
			build_objectCellKey   : 'cells',   // object key containing table cells (within the rows object)
			build_objectHeaderKey : 'headers', // object key containing table headers
			build_objectFooterKey : 'footers'  // object key containing table footers
		}
	});

});

Result

Setup - Object (json file via ajax)

Notes

  • The important difference between this demo and the javascript variable demo above is that this one retrieves a JSON file:
    • Set the build_source option to contain any ajax settings to load the json.
    • To load the json file, set the url option to point to the json file and the dataType set to "json".
    • The remaining default settings were left out of the example below.
  • Please see the "Object (javascript variable)" section above for more details on how to set up the JSON for this demo.
  • Note that JSON formatting is very specific - only double quotes (") can be used to wrap attributes, all keys must be wrapped in quotes, no comments, etc.
  • Always verify that the JSON is valid (use JSONLint) and realize that browsers like Chrome will not allow you to access locally hosted (desktop) JSON files. Test it with Firefox instead.

Javascript

$(function() {
	$('#object2Table2').tablesorter({
		theme: 'blue',
		widgets: ['zebra'],
		widgetOptions: {
			build_type   : 'json',
			build_source : { url: 'assets/build.json', dataType: 'json' }
		}
	});
});

Build.json file

{
	"headers": [
		[
			{ "text": "First Name", "class": "fname", "width": "20%" },
			"Last Name",
			{ "text": "Age", "class": "age", "data-sorter": false },
			"Total",
			{ "text": "Discount", "class": "sorter-false" },
			{ "text": "Date", "class": "date", "width": "20%" }
		]
	],
	"footers": "clone",
	"rows": [
		[ "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" ],

		{ "newTbody": true, "class": "tablesorter-infoOnly" },
		{ "cells": [ { "html": "JSON Info Row", "colspan": 6 } ] },

		{ "newTbody": true },
		[ "Bruce", "Evans",    22, "$13.19",  "11%", "Jan 18, 2007 9:12 AM"  ],
		[ "Brice", "Almighty", 45, "$153.19", "44%", "Jan 18, 2001 9:12 AM"  ],

		{ "class": "specialRow",
			"cells": [
				{ "text": "Fred", "class": "fname" },
				{ "text": "Smith", "class": "lname" },
				{ "text": 18, "class": "age", "data-info": "fake ID!, he's only 16" },
				{ "text": "$22.44", "class": "total" },
				"8%",
				{ "text": "Aug 20, 2012 10:15 AM", "class": "date" }
			],
			"data-info": "This row likes turtles"
		}
	]
}

HTML (before)

<div id="object2Table2"></div>

HTML (after)

<div id="object2Table2">
	<table class="tablesorter tablesorter-blue" role="grid">
		<colgroup>
			<col style="width: 20%;">
			<col>
			<col>
			<col>
			<col>
			<col style="width: 20%;">
		</colgroup>
		<thead>
			<tr>
				<th class="fname">First Name</th>
				<th>Last Name</th>
				<th class="age" data-sorter="false">Age</th>
				<th>Total</th>
				<th class="sorter-false">Discount</th>
				<th class="date">Date</th>
			</tr>
		</thead>
		<tbody>
			<tr>
				<td>Peter</td>
				<td>Parker</td>
				<td>28</td>
				<td>$9.99</td>
				<td>20%</td>
				<td>Jul 6, 2006 8:14 AM</td>
			</tr>
			<tr>
				<td>John</td>
				<td>Hood</td>
				<td>33</td>
				<td>$19.99</td>
				<td>25%</td>
				<td>Dec 10, 2002 5:14 AM</td>
			</tr>
			<tr>
				<td>Clark</td>
				<td>Kent</td>
				<td>18</td>
				<td>$15.89</td>
				<td>44%</td>
				<td>Jan 12, 2003 11:14 AM</td>
			</tr>
		</tbody>
		<tbody class="tablesorter-infoOnly">
			<tr>
				<td colspan="6">
					<strong>JSON Info Row</strong>
				</td>
			</tr>
		</tbody>
		<tbody>
			<tr>
				<td>Bruce</td>
				<td>Evans</td>
				<td>22</td>
				<td>$13.19</td>
				<td>11%</td>
				<td>Jan 18, 2007 9:12 AM</td>
			</tr>
			<tr>
				<td>Brice</td>
				<td>Almighty</td>
				<td>45</td>
				<td>$153.19</td>
				<td>44%</td>
				<td>Jan 18, 2001 9:12 AM</td>
			</tr>
			<tr class="specialRow" data-info="This row likes turtles">
				<td class="fname">Fred</td>
				<td class="lname">Smith</td>
				<td class="age" data-info="fake ID!, he's only 16">18</td>
				<td class="total">$22.44</td>
				<td>8%</td>
				<td class="date">Aug 20, 2012 10:15 AM</td>
			</tr>
		</tbody>
		<tfoot>
			<tr>
				<th class="fname">First Name</th>
				<th>Last Name</th>
				<th class="age" data-sorter="false">Age</th>
				<th>Total</th>
				<th class="sorter-false">Discount</th>
				<th class="date">Date</th>
			</tr>
		</tfoot>
	</table>
</div>

Result