views:

43

answers:

4

How can I sort the <option> elements of a <select> tag using JavaScript?

Here is the HTML I have:

<form action="example.asp">
<div>
<select size="3">
<option value="op2" >Option 2</option>
<option value="op1">Option 1</option>
<option value="op4">Option 4</option>
<option value="op3">Option 3</option>

</select>
</div>
</form> 
+1  A: 
<script language="JavaScript" type="text/javascript">
function sortlist() {
var lb = document.getElementById('mylist');
arrTexts = new Array();

for(i=0; i<lb.length; i++)  {
  arrTexts[i] = lb.options[i].text;
}

arrTexts.sort();

for(i=0; i<lb.length; i++)  {
  lb.options[i].text = arrTexts[i];
  lb.options[i].value = arrTexts[i];
}
}
</script>


<form action="#">
<select name=mylist id=mylist size=5>
<option value="Anton">Anton
<option value="Mike">Mike
<option value="Peter">Peter
<option value="Bill">Bill
<option value="Carl">Carl
</select>
<br>
<a href="javascript:sortlist()">sort</a>
</form>
Pranay Rana
i dont need to click and sort. its shoult be sort while its loading
Tree
than call this function in body load event
Pranay Rana
@Tree Then just call sortlist() from the <script> element.
petsson
A: 

This little bit of algorithmic wizardry should do the trick:

<form action="example.asp">
<div>
<select size="3">
<option value="op1">Option 1</option>
<option value="op2">Option 2</option>
<option value="op3">Option 3</option>
<option value="op4">Option 4</option>

</select>
</div>
</form> 
David
This is not for fun !
Tree
@Tree: Sorry! But seriously, your question didn't make it clear that you needed to sort arbitrary lists of options. (Why **do** you need to do that in JavaScript, anyway? Are they generated client-side?)
David
Sorting the data before sending it to the client makes the most sense, unless you have odd restrictions that you haven't mentioned.
David Dorward
+4  A: 

You should think about it on the pre html-creation level. If you are generating them from some kind of list or by dynamic page mechanism then sort them before you generate your option elements - thats the clearest way ;)

ŁukaszW.pl
+1  A: 

You can sort an array by properties of the objects. Let's consider this sample markup:

<select name="mySelect" id="mySelect>
  <option id="opt3" value="val3">Value 3</option>
  <option id="opt1" value="val1">Value 1</option>
  <option id="opt2" value="val2">Value 2</option>
</select>

And now let's look at a Javascript function that will sort the options of any <select>:

function sortOptionsByValue(x,y) {
    // we are dealing with an options array, so the x and y args
    // represent option elements; and we are going to sort by their value
    return (x.value == y.value) ? 0 : (x.value > y.value) ? 1 : -1;  
}

Then all we have to do is

var mySel = document.getElementById('mySelect');
mySel.options = mySel.options.sort(sortOptionsByValue);

and our options are sorted.

EDITED TO FIX TYPO: mySel.sort => mySel.options.sort

Robusto