PDA

View Full Version : select an option in a dropdown menu



kkroo
05-19-2006, 11:17 AM
Hello,
Is there a way javascript can select an option in a dropdown by giving its value?

example:

in this dropdown:

<select name="choices" size="1">
<option value="choice1">Choice 1</option>
<option value="choice2">Choice 2</option>
<option value="choice3">Choice 3</option>
</select>

I would like javascript to do this:

make an option in the dropdown "choices" selected where the value is = choice2

Thanks

Twey
05-19-2006, 11:44 AM
Not directly by value, no. Try this:
function selectValueFromSelect(/*HTMLSelectElement*/ sel, /*String*/ val) {
for(var i=0;sel.options[i].value != val;i++) void(0);
sel.selectedIndex = i;
}

kkroo
05-19-2006, 12:21 PM
i am a javascript noob, so could you please show me an example?

Twey
05-19-2006, 01:06 PM
Of how to use the function? Of course...

selectValueFromSelect(document.getElementsByName("choice")[0], "choice2");Better than document.getElementsByName() would be to use the forms and elements collections.

kkroo
05-19-2006, 01:56 PM
Thank you a lot, that worked great