开发者

sort select menu alphabetically?

开发者 https://www.devze.com 2023-02-16 06:19 出处:网络
I\'ve got the following select menu (jsFiddle): <select> <option value=\"volvo\">Cars</option>

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 valu开发者_StackOverflow中文版e="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.


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.


My first approach was similar to Koolinc's, using Array.prototype.slice to convert the <select> element's children NodeList to an array. However, this doesn't work in Internet Explorer 8 and lower so I changed it to extract, sort and then re-insert:

var sel = document.getElementsByTagName("select")[0],
    opts = [];

// Extract the elements into an array
for (var i=sel.options.length-1; i >= 2; i--)
    opts.push(sel.removeChild(sel.options[i]));

// Sort them
opts.sort(function (a, b) { 
    return a.innerHTML.localeCompare(b.innerHTML);
});

// Put them back into the <select>
while(opts.length)
    sel.appendChild(opts.shift());

Working demo: http://jsfiddle.net/3YjNR/2/


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/


I would start by giving a class name to all of the entries I want to sort, and giving and ID to the select:

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

as for the javascript

 var mylist = $('#sortableCars');
 var listitems = mylist.children('option.sortMe').get();
 listitems.sort(function(a, b) {
    var compA = $(a).text().toUpperCase();
    var compB = $(b).text().toUpperCase();
    return (compA < compB) ? -1 : (compA > compB) ? 1 : 0;
 })
 $.each(listitems, function(idx, itm) { mylist.append(itm); });
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号