Shami's Blog

DevOps because uptime is not optional

Ordering Select Options With Javascript

I’ve been building trivial web pages for automating tasks for years, but one of things that bothered me the most was having to manually order the OPTIONSs inside SELECTs. I don’t remember where I got the code from but just wanted to share

 1<script type="text/javascript">
 2function sortlist(){
 3	var cl = document.getElementById('SELECT_TO_SORT');
 4	var clTexts = new Array();
 5
 6	for(i = 0; i < cl.length; i++){
 7		clTexts[i] =
 8		cl.options[i].text.toUpperCase() + "," +
 9		cl.options[i].text + "," +
10		cl.options[i].value + "," +
11		cl.options[i].selected;
12	}
13
14	clTexts.sort();
15
16	for(i = 0; i < cl.length; i++){
17		var parts = clTexts[i].split(',');
18
19		cl.options[i].text = parts[1];
20		cl.options[i].value = parts[2];
21	}
22	cl.options[0].selected=true;
23}
24
25sortlist();
26</script>

About Me

Dev gone Ops gone DevOps. Any views expressed on this blog are mine alone and do not necessarily reflect the views of my employer.

Categories