How do I make my HTML table sortable?

I’m putting together a website as a school project, which shows the results you got in each subject. I’d like my table to be sortable so that a user can select which column to sort on, just like Excel. How do I do this in HTML?


Well, HTML on it’s own isn’t going to cut it this time. HTML is a language that you use to define what goes into a web page, but it doesn’t allow for the sort of dynamic transitions you’re talking about. For this, you need to start looking into Javascript, or even better, one of my favourite libraries: jQuery.

In fact, there’s a plugin for jQuery called Tablesorterwhich will do just what you’re talking about. To use the tablesorter plugin, include the jQuery library and the tablesorter plugin inside the <head> tag of your HTML document:
<script type="text/javascript" src="/path/to/jquery-latest.js"></script> 
<script type="text/javascript" src="/path/to/jquery.tablesorter.js"></script>

Start by telling tablesorter to sort your table when the document is loaded:
$(document).ready(function() 
    { 
        $("#myTable").tablesorter(); 
    } 
);

Click on the headers and you’ll see that your exam tables are now sortable! You’ll have to make sure that your table uses THEAD and TBODY tags, but that should be pretty standard if you’re building your HTML correctly.

Download Tablesorter here

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.