views:

21

answers:

2

Is this most efficient way of setting a select/option box with javascript?

<select id='sel_activity'>
<option value='CYC'>Cycle Count</option>
<option value='INV'>Inventory Count</option>
<option value='INVDROP'>Inventory Drop off</option>
<option value='INVPICK'>Inventory Pick up</option>
<option value='TRAIN'>Training</option>
</select>

<script type="text/javascript">

var select = 'CYC';
var myselect=document.getElementById("sel_activity")
for (var i=0; i<myselect.options.length; i++){
 if (myselect.options[i].value == select)
 {
 myselect.options[i].selected = true;
 }
 else
 {
 myselect.options[i].selected = false;
 } 
} 
</script>
+1  A: 

as long as your values are unique, you can use document.getElementById("sel_activity").value='CYC' instead

bemace
thanks, that's a great improvement
robert
A: 

If you're going for speed over code size, this tweak is slightly faster:

var myselect=document.getElementById("sel_activity");
var len = myselect.options.length;
for (var i=0; i<len; i++){

Minor note: You are missing a ; at the end of the first line in my snippet.

michael