Saturday, May 11, 2024
 Popular · Latest · Hot · Upcoming
70
rated 0 times [  77] [ 7]  / answers: 1 / hits: 42324  / 14 Years ago, thu, august 12, 2010, 12:00:00

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>

More From » html

 Answers
5
<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>

[#95941] Tuesday, August 10, 2010, 14 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
harleyaleenag

Total Points: 678
Total Questions: 121
Total Answers: 105

Location: Papua New Guinea
Member since Thu, Jul 9, 2020
4 Years ago
harleyaleenag questions
Thu, May 5, 22, 00:00, 2 Years ago
Wed, Aug 19, 20, 00:00, 4 Years ago
;