Tuesday, July 28, 2015

Sort table of links with Tablesorter jQuery plugin

Assuming you have a table of links (link a portal) in your website like the following:

<table class="tablesorter" id="tbl1">
<thead>
<tr>
<th>
Faculty
</th>
</tr>
</thead>
<tbody>
<tr>
<td><a href="#link1">A link</a></td>
</tr>
<tr>
<td><a href="#link2">G Link</a></td>
</tr>
<tr>
<td><a href="#link3">H Link</a></td>
</tr>
<tr>
<td><a href="#link4">B Link</a></td>
</tr>
<tr>
<td><a href="#link5">K Link</a></td>
</tr>
<tr>
<td><a href="#link6">U Link</a></td>
</tr>
<tr>
<td><a href="#link7">C Link</a></td>
</tr>
</tbody>
</table>

It is not in any order at all, and you want to sort it alphabetly but don't want to edit the html manually. Tablesort jQuery plugin will save your life:

Tablesorter github repo: https://github.com/christianbach/tablesorter

1. First download (from the git repo above) and include the plugin in your html page:

<script type="text/javascript" src="/path/to/jquery-latest.js"></script>
<script type="text/javascript" src="/path/to/jquery.tablesorter.js"></script>

2. Markup your table to have the standard table tags (<thead> and <tbody>)

3. Add the following script to your page: you need to create a links parser to remove the <a> tag before sorting:

<script type="text/javascript">
    // add parser through the tablesorter addParser method 
    $.tablesorter.addParser({
        // set a unique id 
        id: 'links',
        is: function(s)
        {
            // return false so this parser is not auto detected 
            return false;
        },
        format: function(s)
        {
            // format your data for normalization 
            return s.replace(new RegExp(/<.*?>/),"");
        },
        // set type, either numeric or text
        type: 'text'
    }); 


    // Apply "links" parser to the appropriate column
    $(document).ready(function()
    {
        $("#tbl1").tablesorter({
            headers: {
                0: {
                    sorter: 'links'
                }
            }
    });
</script>

Note that if your links contain some strange tags or character like icons before the text, It better to remove them before sorting (then add it back later)

4. Refresh your html page, click the header (th) to sort your table

5. Cool

Reference:
[0] http://stackoverflow.com/questions/1458906/jquery-tablesorter-sorting-by-link-url-rather-than-link-content
[1] http://tablesorter.com/docs/index.html