Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 890
Wooble Avatar asked Apr 12 '11 16:04

Wooble


1 Answers

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;
  }
}
like image 111
David Waters Avatar answered Oct 21 '22 13:10

David Waters