Wooble Wooble - 1 year ago 45
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>

I know I can select the first option with


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 Source
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;