A very simple and common issue a Javascript newbie often faces is how to select a dropdown option dynamically by value. People who are working for long with Javascript would solve it in minutes, but hey, this is for a newbie, remember?
So this is a simple function I wrote to do the work.
function selectItemByValue(elmnt, value){
for(var i=0; i < elmnt.options.length; i++)
{
if(elmnt.options[i].value == value)
elmnt.selectedIndex = i;
}
}
Parameters
elmnt: This is the select box taken by functions like "getElementById" or any other way.
value: This is the value which needs to be selected from the options of elmnt.
Example
Lets say you have an HTML select box like below:
<select name="numbers" id="numbers">
<option value="1">One<option>
<option value="2">Two<option>
<option value="3">Three<option>
<option value="4">Four<option>
</select>
I have put an id in the select field to make it easy to get it by ID in a bunch of select fields. What we need to do is, first get the element object and pass it to the function along with the value you want to select. Lets say, we want to select Three. So our Javascript code should look like this:
<script language="javascript">
var number = document.getElementById('numbers');
selectItemByValue(number, 3);
</script>
See it in action


#1 by R. Hunter on June 24, 2012 - 1:03 pm
Very nice… especially for long selects. Cheers.
#2 by William on September 12, 2012 - 9:05 pm
Thank you! Visiting other sites none of them explain that JavaScript simply has an issue with selecting by value and it’s necessary to iterate through all values to find it and select it.
I just wasn’t sure if I was using .selectedValue the wrong way but appears that can’t be used at all to set.