Tutorial for the Table sorting JavaScript

So you’ve decided you want to use this table sorting javascript to sort your tables? Just follow this short tutorial on how to do it, and in five minutes time, your table should sort.

Suppose you have this table:

<table>
<tr>
 <th>Numbers</th>
 <th>Alphabet</th>
 <th>Dates</th>
 <th>Currency</th>
</tr>
<tr>
 <td>1</td>
 <td>Z</td>
 <td>02-02-2004</td>
 <td>€ 5.00</td>
</tr>
<tr>
 <td>4</td>
 <td>w</td>
 <td>01.Jan.2005</td>
 <td>€ 4.20</td>
</tr>
<tr>
 <td>5</td>
 <td>V</td>
 <td>05/12/2006</td>
 <td>€ 7.15</td>
</tr>
<tr>
 <td>15</td>
 <td></td>
 <td></td>
 <td>€ 29.55</td>
 <td></td>	
</tr>
</table>

To get this table to sort, you have to give it a class sortable, and an id of your choice, so the first line of your table should now look something like this:

<table class="sortable" id="sortable_example">

In the head-section of your page, include the following:

<script type="text/javascript" src="sortable.js"></script>

Now add the following example CSS to your stylesheet, you can ofcourse change colours and/or add styles:

.odd {
 background-color: #ddd;
}
.even {
 background-color: #fff;
}

Extra options

The script offers a few extra options, they are:

  • By adding a class sortbottom to a row, this row wil be inserted last in your table, this is very useful for totals.
    This would make your last row look like this:

    <tr class="sortbottom">
     <td>15</td>
     <td></td>
     <td></td>
     <td>€ 29.55</td>
     <td></td>	
    </tr>

    You can then of course also style this footer with CSS.

  • By adding a class unsortable to a cell in the first row, this column will be made unsortable. The first row could
    then look like this:

    <tr>
     <th>Numbers</th>
     <th>Alphabet</th>
     <th>Dates</th>
     <th>Currency</th>
     <th class="unsortable">Unsortable</th>
    </tr>

If you do all this, your table should look something like this example table.