As I set out on re-writing the interface for my systems database, on thing I knew I wanted to implement was better sorting, and pagination. In v1 I implemented sorting through GET statements, and requerying the database according to the choice of column and direction.
First of all, your table needs to be setup in the following standard structure:
<table class='sortable paginated'>
<th class='sort-alpha'><span class='ui-icon ui-icon-arrowthick-2-n-s'></span>Column 1</th>
Three quick things you’ll notice, 1) the two classes on the table (sortable and paginated), 2) the class on the TH (sort-alpha), and 3) the SPAN is for a jQuery UI icon feature. I’m going to state the obvious here, if you include the class “sortable” on the table, then it will be made sortable, and if you include the class “paginated”, the table will be paginated.
The class on the TH tells it how to process the sorting: sort-alpha, sort-numeric, and sort-date are all available. The first click on the header sorts ascending, the second sets it to descending, the third back to ascending, and so on.
A nice side benefit of using sortable or paginated on the table is that it also dynamically adds an “odd” or “even” class to each row for styling purposes. And this odd/even is refactored with every sort.
I did have to make a few modifications to the jQuery code I found.
Next, the sorting, on the first click, would add the sorted-asc class, and the second would add the sorted-desc class, but the second would not remove the sorted-asc class. This kept it from sorting it decendingly. Because jQuery is chainable, I just added a .removeClass(‘sorted-asc’) for the even numbered clicks, and a .removeClass(‘sorted-desc’) for the odd-numbered clicks. I also threw in some similar code that acts the same way to stylize the TH in line with the jQuery UI plugin, changing the SPAN arrow class, and on all of the TH blocks adding/removing a “ui-state-active” class where appropriate.
The last change I made was adding a “View All” option. A coworker asked if I could do that, since it is nice to see the full table in non-paged sometimes. To achieve this I added a View All link to the end of the paging links, and when this link is clicked it re-paginates the table setting the “current page” back to zero (the first page), with the number per page equal to the number of rows. Then when one of the paged numbers is clicked it changes back into the normal mode where number per page is equal to your defined number.
Here is my code. As I said, mostly taken from this tutorial, with my modifications described in this post.