0

I have a <select> element which has some initial values, how can I add a value to the select and then order it alphabetically.

I can add options with some simple JavaScript:

var select = document.getElementById("example-select");
select.options[select.options.length] = new Option('Text 1', 'Value1');

...but that only appends it to the end.

How can I sort a <select> element by JavaScript without using jQuery.

5
  • 1
    possible duplicate of Javascript to sort contents of select element Commented Oct 23, 2012 at 15:06
  • Are the current options sorted? Commented Oct 23, 2012 at 15:07
  • @user1689607 Yes, It's just the added item that doesn't follow the alphabetical order. Commented Oct 23, 2012 at 15:09
  • do you want to order by option value or option text? Are the inital values of the select already ordered so you just need to insert the new one ordered? Commented Oct 23, 2012 at 15:10
  • Is it ordered by the text or by the value? Commented Oct 23, 2012 at 15:10

3 Answers 3

2

give this a try.

var select = document.getElementById("example-select");

var options = select.options;
var newOption = new Option('Text 1', 'Value1');

for (var i = 0, len = options.length; i < len; i++) {
    if (newOption.text.localeCompare(options[i].text) < 0) {
        break;
    }
}

select.insertBefore(newOption, options[i] || null);
Sign up to request clarification or add additional context in comments.

6 Comments

@LazyTarget: Thanks. I had a mistake that I just corrected. Nice thing is that it doesn't require the expensive sort, but presumes a current alphabetical order.
I'll go with this one, seems to be faster.
+1 for localeCompare. :-)
May I suggest using add instead of insertBefore? Same syntax, just feels cleaner.
@Prinzhorn: I think there are some older IE quirks, but otherwise I'd agree that it would be cleaner.
|
2

Try this

var select = document.getElementById('select');

var sorted = Array.prototype.slice.call(select.options).sort(function(a, b) {
    if(a.label < b.label) return -1;
    if(a.label > b.label) return 1;
    return 0;
});

for(var i = 0; i < sorted.length; i++) {
    select.add(sorted[i]);
}

Sorted by label. Just change it for other properties.

Note that options is read only.

https://tinker.io/9720d

Note: does not work IE 8 and below

1 Comment

Try that in IE8. You can't be sure that host objects can be passed to native methods like that without error. There is no specification that says you can, and ECMA-262 says host objects don't have to behave like native objects, so there is a specific warning that they may not (and in IE 8 and lower you can't).
0

There are a couple of methods, one is to create an array of the option values (or text, whatever you want to sort on) and create an object with properties whose names are the option values (or text) and values are references to the options.

Sort the array, then iterate over it, using the member values to get the options from the object, e.g.

function sortOptionsByValue(select) {
  var a = [], o = {}, opt;
  for (var i=0, iLen=select.options.length; i<iLen; i++) {
    opt = select.options[i];
    a.push(opt.value);
    o[opt.value] = opt;
  }
  a.sort();
  while (i--) {
    select.insertBefore(o[a[i]], select.firstChild);
  }
  // Optional, make first option selected
  select.selectedIndex = 0;
}

There are other methods, the above is just one. But it will work in any ECMA-262 compliant browser and doesn't depend on host objects acting like native objects, only that they behave like the W3C DOM Core says they should.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.