Example: Column Sorting

Example: Column Sorting

The datatable-sort module adds column sorting functionality to a basic DataTable.

Table with simple column sorting
Click to Sort Column A
Not Sortable Column B
Click to Sort Column C
Company Bee415-555-1234Sally Spencer
Acme Company650-555-4444John Jones
Industrial Industries408-555-5678Robin Smith
Table with column sorting by data type
Sortable Number
Sortable Date
Sortable string
Sortable string (case sensitive)
1Sun Sep 16 2001 00:00:00 GMT+0000 (Coordinated Universal Time)AA
2Tue Sep 16 2003 00:00:00 GMT+0000 (Coordinated Universal Time)aa
3Fri Sep 16 2005 00:00:00 GMT+0000 (Coordinated Universal Time)ZZ
4Sun Sep 16 2007 00:00:00 GMT+0000 (Coordinated Universal Time)zz

Implementing Sortable Columns

To add column sorting functionality to any DataTable, simply include the datatable-sort module in your use() line and add the sortable: true configuration to the configuration objects of the columns you want to be sortable.

Note: be sure to add the yui3-skin-sam classname to the page's <body> element or to a parent element of the widget in order to apply the default CSS skin. See Understanding Skinning.

<body class="yui3-skin-sam"> <!-- You need this skin class -->

Note, if you want all columns to be sortable, simply set sortable: true on the DataTable instance.

YUI().use("datatable-sort", function(Y) {
    var cols = [
        {key:"Company", label:"Click to Sort Column A", sortable:true},
        {key:"Phone", label:"Not Sortable Column B"},
        {key:"Contact", label:"Click to Sort Column C", sortable:true}
    ],
    data = [
        {Company:"Company Bee", Phone:"415-555-1234", Contact:"Sally Spencer"},
        {Company:"Acme Company", Phone:"650-555-4444", Contact:"John Jones"},
        {Company:"Industrial Industries", Phone:"408-555-5678", Contact:"Robin Smith"}
    ],
    table = new Y.DataTable({
        columns: cols,
        data   : data,
        summary: "Contacts list",
        caption: "Table with simple column sorting"
    }).render("#sort");
});