Alex Rivera | Logout

sort select menu alphabetically?

Asked 2011-03-09T15:41:57.090
9

I've got the following select menu (jsFiddle):

<select>
  <option value="volvo">Cars</option>
  <option value="saab">------------</option>
  <option value="volvo">Volvo</option>
  <option value="saab">Saab</option>
  <option value="mercedes">Mercedes</option>
  <option value="audi">Audi</option>
</select>

Using Javascript, how would I re-sort the list alphabetically, excluding the first 2 options (Cars and -------), which must remain at the top? Thanks in advance for any help.

Edit
Report

1 Answer

14

Being a purist, I would say that at no point was jQuery specifically mentioned or asked for, it may not be in use in this project for one reason or another. Here's an example using pure javascript.

function sortlist(){

 var cl = document.getElementById('carlist');
 var clTexts = new Array();

 for(i = 2; i < cl.length; i++){
    clTexts[i-2] =
        cl.options[i].text.toUpperCase() + "," +
        cl.options[i].text + "," +
        cl.options[i].value + "," +
        cl.options[i].selected;
 }

 clTexts.sort();

 for(i = 2; i < cl.length; i++){
    var parts = clTexts[i-2].split(',');

    cl.options[i].text = parts[1];
    cl.options[i].value = parts[2];
    if(parts[3] == "true"){
        cl.options[i].selected = true;
    }else{
       cl.options[i].selected = false;
    }
 }
}

sortlist();

http://jsfiddle.net/GAYvL/7/

Updated to be case neutral.

answered 2011-03-09T15:54:26.047

Your Answer