Sandbox: JavaScript

Implements support for interactive tables. Mostly used for sorting (but can be used for selection if you want).

Less Component Required

Be sure to include components/htmltable.less in your build.

Basic Usage

ID TimeZone Name GEO Latitude GEO Longitude
22 New York City America/New_York 40.7255 -73.9983
23 San Francisco America/Los_Angeles 37.7587 -122.433
24 Boston America/New_York 42.3583 -71.0603
25 Denver America/Denver 39.734 -105.026
31 Washington, DC America/New_York 38.8964 -77.0447
32 Chicago America/Chicago 41.8858 -87.6181
33 Philadelphia America/New_York 39.8694 -75.2731
<table class="table table-bordered table-striped table-condensed" data-behavior="HtmlTable" data-htmltable-sortable="true">
  <thead>
    <tr>
      <th>
            ID
      </th>
      <th>
            TimeZone
      </th>
      <th>
            Name
      </th>
      <th>
            GEO Latitude
      </th>
      <th>
            GEO Longitude
      </th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>
        22
      </td>
      <td>
        New York City
      </td>
      <td>
        America/New_York
      </td>
      <td>
        40.7255
      </td>
      <td>
        -73.9983
      </td>
    </tr>
    <tr>
      <td>
        23
      </td>
      <td>
        San Francisco
      </td>
      <td>
        America/Los_Angeles
      </td>
      <td>
        37.7587
      </td>
      <td>
        -122.433
      </td>
    </tr>
    <tr>
      <td>
        24
      </td>
      <td>
        Boston
      </td>
      <td>
        America/New_York
      </td>
      <td>
        42.3583
      </td>
      <td>
        -71.0603
      </td>
    </tr>
    <tr>
      <td>
        25
      </td>
      <td>
        Denver
      </td>
      <td>
        America/Denver
      </td>
      <td>
        39.734
      </td>
      <td>
        -105.026
      </td>
    </tr>
    <tr>
      <td>
        31
      </td>
      <td>
        Washington, DC
      </td>
      <td>
        America/New_York
      </td>
      <td>
        38.8964
      </td>
      <td>
        -77.0447
      </td>
    </tr>
    <tr>
      <td>
        32
      </td>
      <td>
        Chicago
      </td>
      <td>
        America/Chicago
      </td>
      <td>
        41.8858
      </td>
      <td>
        -87.6181
      </td>
    </tr>
    <tr>
      <td>
        33
      </td>
      <td>
        Philadelphia
      </td>
      <td>
        America/New_York
      </td>
      <td>
        39.8694
      </td>
      <td>
        -75.2731
      </td>
    </tr>
  </tbody>
</table>

Related Documentation

Note: Not all links in these work.

Behavior Filter: Behavior.HtmlTable

Creates an instance of HtmlTable for an element using the HtmlTable data filter.

See also:

Example

<table data-behavior="HtmlTable" data-htmltable-options="
    'sortable':true, 'selectable':true,
    'parsers':['number', 'string']
">
    <thead>
        <tr>
            <td>column 1</td> <td>column 2</td>
        </tr>
    <thead>
    <tbody>
        <tr>
            <td>1</td> <td>a</td>
            <td>2</td> <td>b</td>
            <td>3</td> <td>4</td>
    </tbody>
</table>

Options

  • sortOnStartup - (boolean; defaults to false) If true the table is sorted on startup. This is expensive; use sparingly.
  • sortIndex - (number) This is the initial column to sort (if sortOnStartup is true). The first th that does not have the noSort class is used unless a th is found with the class defaultSort. If sortOnStartup is false, this is still used to add the classnames and styling to the column as if it were sorted.
  • sortReverse - (boolean) if true, sorts the column reverse on startup (if sortOnStartup is true).
  • parsers - (array) A mapping of parsers for each column of data. See the parsers defined in HtmlTable.Sort.
  • sortable - (booelan; defaults to false) You can also give the table the css class sortable to set this flag to true.
  • classNoSort - (string; defaults to noSort) The string given to column headers that are not sortable.
  • selectable - (boolean; defaults to false) You can also give the table the css class selectable or multiselect to set this flag to true.
  • allowMultiSelect - (boolean; defaults to false) You can also give the table the css class multiselect to set this flag to true.
  • useKeyboard - (boolean; defaults to true) Enables keyboard controls (up/down). You can also give the table the css class noKeyboard to disable this flag.

Class: HtmlTable

Builds table elements with methods to add rows quickly.

Tutorial/Demo

Implements

HtmlTable Method: constructor

Syntax

new HtmlTable([table, options]);

Arguments

  1. table - (mixed; optional) - a Table DOM element or it's id; if you do not specify one, one will be created.
  2. options - (object; optional) a key/value set of options.

Options

  • properties - (object) a set of properties for the Table element; defaults to {cellpadding:0, cellspacing:0, border:0}
  • rows - (array) an array of row objects (see HtmlTable.push)
  • headers - (array) a row that is injected in the thead; required for sorting.

Example

var myTable = new HtmlTable({
    properties: {
        border: 1,
        cellspacing: 3
    },
    headers: ['fruits', 'colors'],
    rows: [
        ['apple', 'red'],
        ['lemon', 'yellow']
    ]
});
myTable.inject($('someContainer'));

//ALSO

var myTable = new HtmlTable($('existingTable'));
myTable.push(['data','goes','here']);

HtmlTable Method: push

Inserts a new table row. To push several at once, see (see HtmlTable.pushMany)

Syntax

myHtmlTable.push(row, rowProperties, target, tag, where);

Arguments

  1. row - (array or element) the data for the row or TR element.
  2. rowProperties - (object; optional) the properties for the row (class, id, styles, etc)
  3. target - (element; optional) The element that the row is injected into, before, after, etc. Defaults to the table body.
  4. tag - (string; optional) The type of element to create (td or th); defaults to td.
  5. where - (string; optional) the argument passed to Element.inject that specifies where the row is inserted relative to the specified target (before, after, top, bottom, etc)

Row data

Row data can be in either of two formats. Note that they can be mixed and matched.

  • simple - (array) an array of strings, elements and element collections that will be inserted into each table data

OR

  • detailed - (array) an array of objects with definitions for content and properties for each table data

Note that it can also be an actual TR element.

Examples

//example of 'simple' rows
myTable.push(['value 1', 'value 2', 'value 3'], {
    'class': 'tableRowClass'
}); //new row


//detailed rows
myTable.push([
    { //can specify data AND properties
        content: 'value 4',
        properties: {
            colspan: 2,
            'class': 'doubleWide',
            style: '1px solid blue'
        }
    },
    'value 5' //can just be data; mixing and the two in the same row is fine
]);


//RESULT:
<table cellpadding="0" cellspacing="0" border="0">
    <tr class="tableRowClass">
        <td>value 1</td>
        <td>value 2</td>
        <td>value 3</td>
    </tr>
    <tr>
        <td colspan="2" class="doubleWide" style="1px solid blue">value 4</td>
        <td>value 5</td>
    </tr>
</table>

Returns

  • (object) an object containing the tr and td tags.

Example of Object Returned

{tr: theTableRow, tds: [td, td, td]}

HtmlTable Method: update

Update a table row

Syntax

myHtmlTable.update(tr, row);

Arguments

  1. tr - (TR element) the row to update
  2. row - (array or element) the data for the row or TR element. Same as the row data sent to HtmlTable.push

Returns

  • (object) an object containing the tr and td tags.

HtmlTable Method: pushMany

Inserts a group of rows into the table.

Syntax

myHtmlTable.push(rows, rowProperties, target, tag, where);

Arguments

  1. rows - (array) An array of row data objects (see HtmlTable.push)
  2. rowProperties - (object; optional) the properties for the row (class, id, styles, etc)
  3. target - (element; optional) The element that the row is injected into, before, after, etc. Defaults to the table body.
  4. tag - (string; optional) The type of element to create (td or th); defaults to td.
  5. where - (string; optional) the argument passed to Element.inject that specifies where the row is inserted relative to the specified target (before, after, top, bottom, etc)

Example

//example of 'simple' rows
myTable.push([
        [1, 'one'],
        [2, 'two'],
        [3, 'three']
    ], {
    'class': 'tableRowClass'
});

The above example would produce a table with 3 rows each with the class tableRowClass.

Returns

HtmlTable method: empty

Empties the tbody of the table.

Syntax

myTable.empty();

Returns

  • (object) This instance of HtmlTable.

HtmlTable method: set

Sets the contents of the header or footer.

Syntax

myTable.set(what, rowArray);

Arguments

  1. what - (string) either 'headers' or 'footers'
  2. rowArray - (array) an array of header information; same as the row data sent to HtmlTable.push

Returns

  • (object) The row data (same as returned by the push method).

HtmlTable method: toElement

If you pass an instance of HtmlTable into the $ or document.id function it will return the actual table Element.

Examples

document.id(myHtmlTable).setStyle('color', 'blue');

$(myHtmlTable) == myHtmlTable.table; // true

HtmlTable methods: Element methods

This class implements the following Element methods:

  • adopt
  • inject
  • wraps
  • grab
  • replaces
  • empty
  • dispose

These will execute these methods on the table element.

Arguments

Each method accepts exactly the same arguments as the Element equivalent.

Returns

  • (object) This instance of HtmlTable.

Example

myHtmlTable.inject(document.body);
//same as:
document.id(myHtmlTable).inject(document.body);

Type: Element

Extends the Element Type with a reference to its HtmlTable instance.

Element property: HtmlTable

Syntax

myElement.retrieve('HtmlTable'); //the instance of HtmlTable for the element

Class: HtmlTable.Sort

Makes headers of HtmlTable clickable to sort the rows.

Refactors

HtmlTable Method: constructor

Syntax

new HtmlTable([table, options]);

Arguments

  1. table - (mixed; optional) - a Table DOM element or it's id; if you do not specify one, one will be created.
  2. options - (object; optional) a key/value set of options.

Options

  • all options defined by HtmlTable, plus:
  • sortIndex - (number) the row to sort on startup; defaults to 0. Set to null if you don't want to sort on startup.
  • sortReverse - (boolean) if true, the initial sorted row will be sorted in reverse. Defaults to false.
  • parsers - (array) a mapping of parsers for each column of data. See section on parsers below.
  • defaultParser - (string) if no parsers are defined and they cannot be auto detected, which parser to use; defaults to 'string'
  • classSortable - (string) the class to add to the table when sorting is enabled; defaults to 'table-sortable'
  • classHeadSort - (string) the class to add to the th that has the current sort (applied when sort order is forward); defaults to 'table-th-sort'
  • classHeadSortRev - (string) the class to add to the th that has the current sort (applied when sort order is reverse); defaults to 'table-th-sort-rev',
  • classNoSort - (string) if a th has this class, it will not be sortable; defaults to 'table-th-nosort'
  • classGroup - (string) class applied to td elements when more than one has the same value; defaults to 'table-tr-group',
  • classGroupHead - (string) class applied to the first td in a group of td elements that have the same value; defaults to 'table-tr-group-head'
  • classCellSort - (string) the class applied to td elements that are in the current sorted column. defaults to 'table-td-sort'
  • classSortSpan - (string) the class applied to a span element injected into the th headers when sorting is enabled; useful for adding an arrow background for the sorted column to indicate the sort direction. defaults to 'table-th-sort-span'
  • sortable - (boolean) enables the sortable feature on invocation. Defaults to false.
  • thSelector - (string defaults to 'th') the string selector used in delegating sort events.

Events

  • sort - callback executed when a column is sorted; passed the tbody and the index of the column sorted.

Note

Your Table must have a thead with th elements for each column (these are what the user clicks on to sort stuff). If your table doesn't have headers already, you can specify them with the headers option or use the setHeaders method.

HtmlTable Method: sort

Sorts a column.

Syntax

myHtmlTable.sort(index, reverse, prepare[, sort]);

Arguments

  1. index - (number) the index of the column to sort
  2. reverse - (boolean) reverses the sort if true; defaults to false
  3. prepare - (boolean) if the sort has a secondary sort, set this value to true on the first sort, and false on the second. For example, if you sorted a directory list of files first by type and then secondly by file size, you would sort on type and pass true and then sort on size and pass false.
  4. sort - (function, optional) this custom function will be used to sort the column. The parameters passed to sort are objects with position and value.

Returns

  • (object) This instance of HtmlTable.

HtmlTable method: enableSort

Enables the sortable features of the table.

Syntax

myTable.enableSort();

Returns

  • (object) This instance of HtmlTable.

HtmlTable method: disableSort

Disables the sortable features of the table.

Syntax

myTable.disableSort();

Returns

  • (object) This instance of HtmlTable.

HtmlTable method: reSort

Reapplies the current sort. Note that this is called whenever new rows are added.

Syntax

myTable.reSort();

Returns

  • (object) This instance of HtmlTable.

HtmlTable Method: serialize

Return an object storing the sort state of the table.

Syntax

      myTable.serialize();

Returns

  • (object) Object containing sort state of the table.

HtmlTable Method: restore

Restores the sort state of the table from an object passed in.

Syntax

      myTable.restore(tableState);

Arguments

  1. tableState - Object created by HtmlTable.serialize() which contains the sort state of the table.

Object: HtmlTable.Parsers

There are numerous parsers used by HtmlTable to determine the sort order of data. A column of numbers, for example, will be sorted numerically, while a column of dates will be sorted by their date order. The HtmlTable.Parsers object contains a group of objects each with a regular expression and a function applied when that expression matches the content.

Example

HtmlTable.Parsers.number = {
    match: /^\d+[^\d.,]*$/,
    convert: function() {
        return this.get('text').toInt();
    },
    number: true
};

Properties

  • match - (regular expression) Used when autodetecting the type of a particular table value.
  • convert - (function) Executed on a particular table cells to parse its value for sorting. The value returned by this function is the value sorted against. The context of this function refers to a particular table cell. This will not update your table cell's html.
  • number - (boolean; optional) Numerical parsers should have this flag for proper sorting.

Included Parsers

  • date - sorts for date formats that are matched by Date.parse
  • input-checked - sorts checkbox inputs into those that are checked and are not checked
  • input-value - sorts based on the value inside text inputs
  • number - sorts on integers
  • numberLax - sorts on integer values that might be mixed with other data.
  • float - sorts on float values
  • floatLax - sorts on float values that might contain other data.
  • string - an alpha sort
  • title - sorts on the title property of the table data element

Array: HtmlTable.ParserPriority

HtmlTable.ParserPriority is an array of parser names which define the priority in which your table data is evaluated for sorting. By default it is defined to test from most specific parser to most general. The default ordering is:

HtmlTable.ParserPriority = ['date', 'input-checked', 'input-value', 'float', 'number']; //if no match, defaults to string

Static Method: HtmlTable.defineParsers

Because HtmlTable.Parsers are run in the order defined by the HtmlTable.ParserPriority above, merely defining a custom parser on the HtmlTable.Parser object will produce no results. Therefore this is a static method which will both define your parser on the HtmlTable.Parser namespace as well as add your parser to the top of the HtmlTable.ParserPriority list.

Syntax

HtmlTable.defineParsers({
    foo: {
        match: /foo/,
        convert: function(){...},
        number: false
    }
});