Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

sort select menu alphabetically?

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.

like image 951
Skizit Avatar asked Mar 09 '11 15:03

Skizit


2 Answers

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.

like image 90
Jeff Parker Avatar answered Sep 30 '22 07:09

Jeff Parker


This is just a more generic answser based on @Jeff Parker's one!

function sortSelect(select, startAt) {
    if(typeof startAt === 'undefined') {
        startAt = 0;
    }

    var texts = [];

    for(var i = startAt; i < select.length; i++) {
        texts[i] = [
            select.options[i].text.toUpperCase(),
            select.options[i].text,
            select.options[i].value
        ].join('|');
    }

    texts.sort();

    texts.forEach(function(text, index) {
        var parts = text.split('|');

        select.options[startAt + index].text = parts[1];
        select.options[startAt + index].value = parts[2];
    });
}

I have also created a fiddle; http://jsfiddle.net/4u86B/1/

like image 43
Renato Gama Avatar answered Sep 30 '22 06:09

Renato Gama