Sortable HTML Tables

| | Comments (0)

A while back I needed to make a sortable table. A quick search revealed sorttable, a javascript and CSS solution. This seemed to be exactly what I was looking for.

However, as I dug a little deeper into the javascript I realized that I was changing so much that a whole rewrite was in order. Since I had simultaneously discovered the fantastic prototype library, I decided to use it in my rewrite.

And thus, sortable.js was born.

This library can turn a table such as:

NameDate of BirthSalary
Smith, Jane01 April 1966$26000.00
Smith, John31 December 1970$35001.00
Appleby, Jackson01 January 1978$92500.00
Zacharia, Isaac13 May 1977$32000.00
$185501

To this:

NameDate of BirthSalary
Smith, Jane01 April 1966$26000.00
Smith, John31 December 1970$35001.00
Appleby, Jackson01 January 1978$92500.00
Zacharia, Isaac13 May 1977$32000.00
Total:$185501

To use the sortable.js library do the following:

  1. Add the javascript libraries:

    <script src="prototype.js"></script>
    <script src="sortable.js"></script>
    
  2. Mark the table as sortable:

    <table class="sortable">
        <thead> Header Rows always stay at the top. </thead>
        <tbody> ... </tbody>
        <tfoot> Footer rows always stay at the bottom. </tfoot>
    </table>
    
  3. Optionally define css style for sorted columns:

    <style type="text/css">
        .sortable thead, .sortable tfoot
        { font-weight: bold; }
        .sortable thead td 
        { 
            background:url( sortable.png ) center right no-repeat; 
            cursor: pointer; 
        }
        .sortable thead td.up 
        { background: url( sort-up.png ) center right no-repeat; }
        .sortable thead td.down 
        { background: url( sort-down.png ) center right no-repeat; }
    </style>
    
  4. There is no step 4.

Please note, sortable.js requires prototype 1.5.0, which at the time of writing is only available in release candidate form as part of the scriptaculous library. I hope somebody finds this library useful. If you have any questions or comments, feel free to send an email to kovax.org@gmail.com.

Leave a comment