My Blog: Sorting Tables

03 February 2017

One of the nicest things about spreadsheets is that you can reorder columns alphabetically just by clicking a "sort" button. Using JQuery, you can now do this for tables in your web pages.

I want to add column sorting to a table in my documentation for the University Project. After quickly reading a few reviews online, I realised that the best way to do this was with an existing JQuery add-on. The best that I could find, that didn't require any substantial changes to my existing tables was Tablesorter.

After downloading the ZIP file and installing the code under my ~/Frontend/Libraries/ directory, I opened my CMS template function BaileyWeb.University.Documentation.HeadMetadata and added a line to load the add-on:

<script id="Tablesorter" type="text/javascript" src="/Frontend/Libraries/Tablesorter/jquery.tablesorter.min.js"></script>

Next, on to the scripts file university.documentation.js to add in the trigger code for a specific class attribute on my tables:

$(document).ready(function () {
    // Tablesorter:

Lastly, I need to style the headings with CSS:

table.sortabletable th.header {
    padding-left: 20px;
    background-image: url('/Frontend/Images/University.Documentation/sortable-up-down.png');
    background-repeat: no-repeat;
    background-position: 8px 50%;

table.sortabletable th.header.headerSortDown {
    background-image: url('/Frontend/Images/University.Documentation/sortable-down.png');

table.sortabletable th.header.headerSortUp {
    background-image: url('/Frontend/Images/University.Documentation/sortable-up.png');

So long as my tables are correctly formatted, with <thead> and <tbody> sections, the sorting will work for all columns. Here's how it looks (click a table heading to sort):

Key: Value:
Charlie 567
Alpha 200
Echo 30
Bravo 2
Delta 9

comments powered by Disqus