Posted By

noah on 07/10/07


Tagged

javascript menu select sort library forms dhtml options utilities clj


Versions (?)

Sort the OPTIONs in a SELECT menu


 / Published in: JavaScript
 

URL: http://groups.google.com/group/comp.lang.javascript/browse_thread/thread/c6ae2e7084b96c1/ef1bf5e1640c139a?lnk=gst&q=sort+options&rnum=4#ef1bf5e1640c139a

Author: Clyde Ingram

  1. function compareOptionText(a,b) {
  2. /*
  3.   * return >0 if a>b
  4.   * 0 if a=b
  5.   * <0 if a<b
  6.   */
  7. // textual comparison
  8. return a.text!=b.text ? a.text<b.text ? -1 : 1 : 0;
  9. // numerical comparison
  10. // return a.text - b.text;
  11.  
  12. }
  13.  
  14. function sortOptions(list) {
  15. var items = list.options.length;
  16. // create array and make copies of options in list
  17. var tmpArray = new Array(items);
  18. for ( i=0; i<items; i++ )
  19. tmpArray[i] = new
  20. Option(list.options[i].text,list.options[i].value);
  21. // sort options using given function
  22. tmpArray.sort(compareOptionText);
  23. // make copies of sorted options back to list
  24. for ( i=0; i<items; i++ )
  25. list.options[i] = new Option(tmpArray[i].text,tmpArray[i].value);
  26.  
  27. }

Report this snippet  

Comments

RSS Icon Subscribe to comments
Posted By: pbraconnot on April 14, 2013

Very good! After a lo000ooooong search I found here what I needed! Thanks a lot

You need to login to post a comment.