Exforsys.com
 

Sponsored Links

 

jQuery Tutorials

 
Home Tutorials jQuery
 

jQuery - Basic Alphabetical Sorting

 

Learning jQuery - Basic Alphabetical Sorting

Now let's perform a sort on the Title column of the table. We'll need a class on the table header cell so that we can select it properly:


Sample Code
  1.  
  2. <thead>
  3. </thead>
  4.  
  5. <tr>
  6. </tr>
  7.  
  8. <th> </th>
  9.  
  10. <th class="sort-alpha"> </th>
  11. Title
  12. <th> </th>
  13. Author(s)
  14. <th> </th>
  15. Publish Date
  16. <th> </th>
  17. Price
  18.  
  19.  
Copyright exforsys.com




To perform the actual sort, we can use JavaScript's built in .sort() method. It does an in‑place sort on an array, and can take a function as an argument. This function compares two items in the array and should return a positive or negative number depending on the result. Our initial sort routine looks like this:


Sample Code
  1. $(document).ready(function() {
  2. $('table.sortable').each(function() {
  3. var $table = $(this)
  4. $('th', $table).each(function(column) {
  5. if ($(this).is('.sort-alpha')) {
  6. $(this).addClass('clickable').hover(function() {
  7. $(this).addClass('hover')
  8. }, function() {
  9. $(this).removeClass('hover')
  10. }).click(function() {
  11. var rows = $table.find('tbody > tr').get()
  12. rows.sort(function(a, b) {
  13. var keyA = $(a).children('td').eq(column).text().toUpperCase()
  14. var keyB = $(b).children('td').eq(column).text().toUpperCase()
  15. if (keyA < keyB) return -1
  16. if (keyA > keyB) return 1
  17. return 0
  18. })
  19. $.each(rows, function(index, row) {
  20. $table.children('tbody').append(row)
  21. })
  22. })
  23. }
  24. })
  25. })
  26. })
Copyright exforsys.com



The first thing to note is our use of the .each() method to make iteration explicit. Even though we could bind a click handler to all headers with the sort-alpha class just by calling $('table.sortable th.sort-alpha').click(), this wouldn't allow us to easily capture a crucial bit of information—the column index of the clicked header. Because .each() passes the iteration index into its callback function, we can use it to find the relevant cell in each row of the data later


Once we have found the header cell, we retrieve an array of all of the data rows. This is a great example of how .get() is useful in transforming a jQuery object into an array of DOM nodes; even though jQuery objects act like arrays in many respects, they don't have any of the native array methods available, such as .sort().


With .sort() at our disposal, the rest is fairly straightforward. The rows are sorted by comparing the textual contexts of the relevant table cell. We know which cell to look at because we captured the column index in the enclosing .each() call. We convert the text to uppercase because string comparisons in JavaScript are case-sensitive and we wish our sort to be case-insensitive. Finally, with the array sorted, we loop through the rows and reinsert them into the table. Since .append() does not clone nodes, this moves them rather than copying them. Our table is now sorted.


This is an example of progressive enhancement's counterpart, graceful degradation. Unlike with the AJAX solution discussed earlier, we cannot make the sort work without JavaScript, as we are assuming the server has no scripting language available to it in this case. The JavaScript is required for the sort to work, so by adding the "clickable" class only through code, we make sure not to indicate with the interface that sorting is even possible unless the script can run. The page degrades into one that is still functional, albeit without sorting available.


We have moved the actual rows around, hence our alternating row colors are now out of whack:



We need to reapply the row colors after the sort is performed. We can do this by pulling the coloring code out into a function that we call when needed:


Sample Code
  1. $(document).ready(function() {
  2. var alternateRowColors = function($table) {
  3. $('tbody tr:odd', $table).removeClass('even').addClass('odd')
  4. $('tbody tr:even', $table).removeClass('odd').addClass('even')
  5. }
  6.  
  7. $('table.sortable').each(function() {
  8. var $table = $(this)
  9. alternateRowColors($table)
  10. $('th', $table).each(function(column) {
  11. if ($(this).is('.sort-alpha')) {
  12. $(this).addClass('clickable').hover(function() {
  13. $(this).addClass('hover')
  14. }, function() {
  15. $(this).removeClass('hover')
  16. }).click(function() {
  17. var rows = $table.find('tbody > tr').get()
  18. rows.sort(function(a, b) {
  19. var keyA = $(a).children('td').eq(column).text().toUpperCase()
  20. var keyB = $(b).children('td').eq(column).text().toUpperCase()
  21. if (keyA < keyB) return -1
  22. if (keyA > keyB) return 1
  23. return 0
  24. })
  25. $.each(rows, function(index, row) {
  26. $table.children('tbody').append(row)
  27. })
  28. alternateRowColors($table)
  29. })
  30. }
  31. })
  32. })
  33. })
Copyright exforsys.com




This corrects the row coloring after the fact, fixing our issue:




Read Next: jQuery - The Power of Plug-ins



 

 

Comments



Post Your Comment:

Members Please Login
Your Name:*
e-mail ID:(required for notification)*
Image Verification: 
 
 Subscribe    

Sponsored Links

 

Subscribe via RSS


Get Daily Updates via Subscribe to Exforsys Free Training via email


Get Latest Free Training Updates delivered directly to your Inbox...

Enter your email address:


 

Subscribe to Exforsys Free Training via RSS
 

 
Partners -  Privacy and Legal Policy -  Site News -  Contact   Sitemap  

Copyright © 2000 - 2010 exforsys.com. All Rights Reserved

Page copy protected against web site content infringement by Copyscape