Given an HTML form element like:
<select id='mydropdown'>
<option value='foo'>Spam</option>
<option value='bar'>Eggs</option>
</select>
I know I can select the first option with
document.getElementById("mydropdown").value='foo'
However, say I have a variable with the value "Spam"; can I select a dropdown item by its text rather than by its value?
var desiredValue = "eggs"
var el = document.getElementById("mydropdown");
for(var i=0; i<el.options.length; i++) {
if ( el.options[i].text == desiredValue ) {
el.selectedIndex = i;
break;
}
}
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