Sort Options in a Select Box


/ Published in: jQuery
Save to your folder(s)

Incredibly useful. Great when you need to remove and add options to selectboxes.


Copy this code and paste it in your HTML
  1. jQuery.fn.sort = function()
  2. {
  3. return this.pushStack([].sort.apply(this, arguments), []);
  4. };
  5.  
  6. jQuery.fn.sortOptions = function(sortCallback)
  7. {
  8. jQuery('option', this)
  9. .sort(sortCallback)
  10. .appendTo(this);
  11. return this;
  12. };
  13.  
  14. jQuery.fn.sortOptionsByText = function()
  15. {
  16. var byTextSortCallback = function(x, y)
  17. {
  18. var xText = jQuery(x).text().toUpperCase();
  19. var yText = jQuery(y).text().toUpperCase();
  20. return (xText < yText) ? -1 : (xText > yText) ? 1 : 0;
  21. };
  22. return this.sortOptions(byTextSortCallback);
  23. };
  24.  
  25. jQuery.fn.sortOptionsByValue = function()
  26. {
  27. var byValueSortCallback = function(x, y)
  28. {
  29. var xVal = jQuery(x).val();
  30. var yVal = jQuery(y).val();
  31. return (xVal < yVal) ? -1 : (xVal > yVal) ? 1 : 0;
  32. };
  33.  
  34. return this.sortOptions(byValueSortCallback);
  35. };

URL: http://rickyrosario.com/blog/sorting-dropdown-select-options-using-jquery/

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.