i want to sort the drop down items using javascript,can anyone tell me how to do this.
-
What do you mean by drop down items? – Gumbo Mar 20 '09 at 16:54
-
How are you getting the data that you are populating the drop down list with? – NoahD Mar 20 '09 at 16:59
-
Does this answer your question? [Javascript to sort contents of select element](https://stackoverflow.com/questions/278089/javascript-to-sort-contents-of-select-element) – Elikill58 Mar 10 '23 at 09:45
8 Answers
You could use jQuery and something like this:
$("#id").html($("#id option").sort(function (a, b) {
return a.text == b.text ? 0 : a.text < b.text ? -1 : 1
}))
But it's probably better to ask why and what you're trying to accomplish.

- 115,249
- 25
- 154
- 140

- 1,366
- 9
- 7
-
3+1 based purely on what it would take to do without jQuery (see answer below). – Sean Bright Mar 20 '09 at 18:16
-
This worked great for me. My drop down is populated on change of another drop down. This code did the trick! Thanks @mastro – shanabus Aug 19 '10 at 15:39
-
<select id="foo" size="10">
<option value="3">three</option>
<option value="1">one</option>
<option value="0">zero</option>
<option value="2">two</option>
</select>
<script>
// WARN: won't handle OPTGROUPs!
var sel = document.getElementById('foo');
// convert OPTIONs NodeList to an Array
// - keep in mind that we're using the original OPTION objects
var ary = (function(nl) {
var a = [];
for (var i = 0, len = nl.length; i < len; i++)
a.push(nl.item(i));
return a;
})(sel.options);
// sort OPTIONs Array
ary.sort(function(a,b){
// sort by "value"? (numeric comparison)
// NOTE: please remember what ".value" means for OPTION objects
return a.value - b.value;
// or by "label"? (lexicographic comparison) - case sensitive
//return a.text < b.text ? -1 : a.text > b.text ? 1 : 0;
// or by "label"? (lexicographic comparison) - case insensitive
//var aText = a.text.toLowerCase();
//var bText = b.text.toLowerCase();
//return aText < bText ? -1 : aText > bText ? 1 : 0;
});
// remove all OPTIONs from SELECT (don't worry, the original
// OPTION objects are still referenced in "ary") ;-)
for (var i = 0, len = ary.length; i < len; i++)
sel.remove(ary[i].index);
// (re)add re-ordered OPTIONs to SELECT
for (var i = 0, len = ary.length; i < len; i++)
sel.add(ary[i], null);
</script>
-
.value comparison will only work for numerics; for lexicographic sorting see the comparator in masto's answer. – bobince Mar 20 '09 at 18:56
-
2Sorry, but I don't understand what's the point of your comment, as I'm sure you have looked ONE line below that numeric comparison that does exactly a, guess what, "lexicographic comparison" on options' "text"?! :( – altblue Mar 20 '09 at 20:22
-
-
1this solution keeps all the attribute attached to the options; in case you use those to store data: it won't be lost on re-ordering. Very nice! this is an alternative to order by one of those attributes in the ary.sort function : var aPosition = parseInt( a.getAttribute('Position') ); var bPosition = parseInt( b.getAttribute('Position') ); return aPosition < bPosition ? -1 : aPosition > bPosition ? 1 : 0; – jrgd Mar 20 '15 at 23:41
You can try JQuery sort function for this work --
HTML CODE -
<select id="ddlList">
<option value="3">Three</option>
<option value="1">One</option>
<option value="1">one</option>
<option value="1">a</option>
<option value="1">b</option>
<option value="1">A</option>
<option value="1">B</option>
<option value="0">Zero</option>
<option value="2">Two</option>
<option value="8">Eight</option>
</select>
JQUERY CODE -
$("#ddlList").html($('#ddlList option').sort(function(x, y) {
return $(x).text().toUpperCase() < $(y).text().toUpperCase() ? -1 : 1;
}));
$("#ddlList").get(0).selectedIndex = 0;
e.preventDefault();
OR
you can also use array sorting for this -
var options = $('#ddlList option');
var arr = options.map(function (_, o) { return { t: $(o).text(), v: o.value }; }).get();
arr.sort(function (o1, o2) { return o1.t.toUpperCase() > o2.t.toUpperCase() ? 1 : o1.t.toUpperCase() < o2.t.toUpperCase() ? -1 : 0; });
options.each(function (i, o) {
o.value = arr[i].v;
$(o).text(arr[i].t);
});

- 8,063
- 9
- 48
- 75
DEPENDS ON JQUERY
function SortOptions(id) {
var prePrepend = "#";
if (id.match("^#") == "#") prePrepend = "";
$(prePrepend + id).html($(prePrepend + id + " option").sort(
function (a, b) { return a.text == b.text ? 0 : a.text < b.text ? -1 : 1 })
);
}
Examples:
<select id="my-list-id"> is sorted with:
SortOptions("#my-list-id");
OR
SortOptions("my-list-id");

- 2,509
- 1
- 14
- 4
-
If you want to sort the items based on the _value_ rather than the text then the function would read: `function (a, b) { return a.value - b.value })` – Chris B Oct 12 '11 at 10:51
Put the option values and text into an array, sort the array, then replace the existing option elements with new elements constructed from the sorted array.

- 124,184
- 33
- 204
- 266
-
here is a link I found which shows how to do this: http://www.w3schools.com/jsref/jsref_sort.asp – mrTomahawk Mar 20 '09 at 17:43
FOR DROPDOWN FOR WHOLE PROJECT
$(document).ready(function () {
$.when($('select').addClass('auto-drop-sort')).then($.fn.sortDropOptions("auto-drop-sort"))
})
/*sort all dropdown*/
$.fn.sortDropOptions = function(dropdown_class){
var prePrepend = ".";
if (dropdown_class.match("^.") == ".") prePrepend = "";
var myParent = $(prePrepend + dropdown_class);
$.each(myParent, function(index, val) {
/*if any select tag has this class 'manual-drop-sort' this function wont work for that particular*/
if ( ! $(val).hasClass('manual-drop-sort') ) {
var selectedVal = $(val).val()
$(val).html($(val).find('option').sort(
function (a, b) {
if ( a.value != -1 && a.value != 0 && a.value != '' ) {
return a.text == b.text ? 0 : a.text < b.text ? -1 : 1
}
})
);
$(val).val(selectedVal)
}else{
/* set custom sort for individual select tag using name/id */
}
});
}

- 457
- 7
- 18
The answers provided didn't really suit my case so I made my own (especially not wanting jQuery). Figured it might help others.
sortDropDown(document.querySelector('select'));
function sortDropDown(d){
//save option values
var existingOptions=d.options;
//keep track of previously selected option
var selectedOpt=d.selectedOptions[0].value;
//turn nodeList into Array of values
existingOptions=[].slice.call(existingOptions).map(function(a){return a.innerText});
//make sure options are unique
existingOptions = existingOptions.filter( function(value, index, self) {
return self.indexOf(value) === index;
});
//sort options
existingOptions.sort();
//keep "All" option as first element
existingOptions.splice(0, 0, existingOptions.splice(existingOptions.indexOf('All'), 1)[0]);
//repleace dropdown contents
var t='';
existingOptions.forEach(function(a){
t+='<option '+(a==selectedOpt?'selected':'')+' value="'+a+'">'+a+'</option>';
});
d.innerHTML=t;
}

- 762
- 1
- 6
- 10
Here is a way you could do it after the fact... But really it would be better to sort the array first, then fill it. If you MUST do it afterward, here... You can also throw in ignore case if you want. You could also not store in sortedOptionsAll and go directly to filling the combo. Your choice. It can be refactored, simplified, etc. This is a general idea though.
<script>
function sortCombo(comboBoxId) {
//get drop down
let comboBox = document.getElementById(comboBoxId);
//create array for storage
let optionsText = [];
let optionsTextSorted = [];
let optionsValues = [];
let sortedOptionsAll = [];
//store in the array
Array.from(comboBox.options).forEach(x => {
optionsText.push(x.text);
optionsValues.push(x.value);
}
);
optionsTextSorted = [...optionsText];
optionsTextSorted.sort();
optionsTextSorted.forEach(x => {
sortedOptionsAll.push({ value: optionsValues[optionsText.indexOf(x)], text: x });
}
);
//clear the combo box
Array.from(comboBox.options).forEach(x => x.text = '');
//fill the combobox
for (let i = 0; i < sortedOptionsAll.length; i++) {
document.getElementById(comboBoxId)[i].text = sortedOptionsAll[i].text;
document.getElementById(comboBoxId)[i].value = sortedOptionsAll[i].value;
}
}
</script>

- 1
- 1