Wooble Wooble - 4 months ago 9
Javascript Question

Selecting an option element from a dropdown by its text value

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?

Answer
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;
  }
}