Wednesday, December 2, 2009

jQuery, tables, and administrative interfaces

A few month ago, I posted about using Jquery to re-imagine simple things. Recently, I've been working with jQuery and jQuery UI quite a bit - in particular in building simple administrative interfaces.

Simple admin interfaces almost always require a table of stuff - users, comments, posts, actions, jobs, whatever - the "things" being administrated. jQuery has a really cool plugin called TableSorter that makes it's incredibly easy to convert a simple HTML table into a fancy, easy-to-read interface.

TableSorter even has a simple pagination capability (see the demo here). The current version (2.0.3) of the paginator requires that you have an html element of class "pagesize" which defines the number of items to display on one page. But the code doesn't actually do an error check to see if that value doesn't exist or if the value is NaN (javascript's fancy way of saying the value there is not a number). So, here's a simple patch to apply to the jquery.tablesorter.pager.js file which will perform the validation & error check.

I found one other drawback of the paginator. By default, the paginator will display something like "1/103" for the current page number and the total number of pages. But, the current code is somewhat limiting. You can change the separator ("/" by default) between the current page number and number of pages, but that's about it. In addition, the code will invoke jQuery's .val() method to display the resulting string. This is also really limiting, since not all elements support using val() to set their contents. For example, invoking .val() on a element does nothing.

So, here's another patch to apply to the jquery.tablesorter.pager.js file which will allow you to register a callback function. By using a callback function, you can control the display as you see appropriate. The callback function is passed 3 arguments:
*func (config, page_active, page_total)
The config parameter is the internal configuration information from the paginator, but the really useful parameters are the other two. page_active is the currently displayed page number. page_total is the total number of pages.

Here's a sample of how you can use the callback:

    .tablesorter({ 'widgets': ['zebra'] })
    'container': jQuery("#jq-pager"),
    'size': 20,
    'positionFixed': false,
    'updatePageDisplayFn': function (config, pg, total)
        jQuery('.pagedisplay_nice').text('Page '
            + pg + ' of ' + total);

This sample code results in displaying the pagination information like this:
Page 1 of 103
in the text area of all elements with the class "pagedisplay_nice". In my HTML page, I have a simple span element in a different place on the page, which looks like this:
<span class="pagedisplay_nice" />
This provides a massive amount of flexibility for the user of TableSorter's Pager plugin.

Hope this helps!

No comments: