I have a select element like this
<select name ="cars">
<option value="frd"> Ford </option>
<option value="hdn"> Holden </option>
<option value="nsn"> Nissan </option>
</select>
I want to set selected to "Holden" with javascript without selected by value. how can I achieve this?
Thanks in advance
update after comment
Use the following to find the option by text and select it
var optionlist = document.getElementById('cars').options;
for (var option = 0; option < optionlist.length; option++ )
{
if (optionlist[option].text == 'Holden')
{
optionlist[option].selected = true;
break;
}
}
demo at http://jsfiddle.net/gaby/vQhfq/
original
When there is no value attribute specified for option elements, they assume the value to be the text.
I would suggest you use an id, so you can easily find the element.
Html
<select name ="cars" id="cars">
<option> Ford </option>
<option> Holden </option>
<option> Nissan </option>
</select>
javascript
document.getElementById('cars').value = 'Holden';
(make sure you run this code, after the select element is created)
demo at http://jsfiddle.net/gaby/Pwb5u/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With