Exforsys.com
 

Sponsored Links

 

jQuery Tutorials

 
Home Tutorials jQuery
 

jQuery - Finessing the Sort Key

 

Learning jQuery - Finessing the Sort Keys

Now we want to apply the same kind of sorting behavior to the Author(s) column of our table. By adding the sort-alpha class to its table header cell, the Author(s) column can be sorted with our existing code. But ideally authors should be sorted by last name, not first. Since some books have multiple authors, and some authors have middle names or initials listed, we need outside guidance to determine what part of the text to use as our sort key. We can supply this guidance by wrapping the relevant part of the cell in a tag:



Sample Code
  1.  
  2. <tr>
  3. </tr>
  4.  
  5. <td> </td>
  6.  
  7. Building Websites with Joomla! 1.5 Beta 1
  8. <td> </td>
  9. <td> </td>
  10. Hagen <span class="sort-key">Graf</span>
  11. <td> </td>
  12. Feb 2007
  13. <td> </td>
  14. $40.49
  15.  
  16. <tr>
  17. </tr>
  18.  
  19. <td> </td>
  20.  
  21. Learning Mambo: A Step-by-Step Tutorial to Building Your Website
  22.  
  23. <td> </td>
  24. Douglas <span class="sort-key">Paterson</span>
  25. <td> </td>
  26. Dec 2006
  27. <td> </td>
  28. $40.49
  29.  
  30. <tr>
  31. </tr>
  32.  
  33. <td> </td>
  34.  
  35. <td> </td>
  36. Moodle E-Learning Course Development
  37. <td> </td>
  38. William <span class="sort-key">Rice</span>
  39. <td> </td>
  40. May 2006
  41. <td> </td>
  42. $35.99
  43.  
Copyright exforsys.com



Now we have to modify our sorting code to take this tag into account, without disturbing the existing behavior for the Title column, which is working well. By prepending the marked sort key to the key we have previously calculated, we can sort first on the last name if it is called out, but on the whole string as a fallback:


Sample Code
  1. $.each(rows, function(index, row) {
  2. var $cell = $(row).children('td').eq(column)
  3. row.sortKey = $cell.find('.sort-key').text().toUpperCase()
  4. + ' ' + $cell.text().toUpperCase()
  5. })
Copyright exforsys.com




Sorting by the Author(s) column now uses the last name:



If two last names are identical, the sort uses the entire string as a tiebreaker for positioning.



Read Next: jQuery - Sorting Other Types of Data



 

 

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