Selecting an option element from a dropdown by its text value

53,758

Solution 1

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

Solution 2

I'd use the selectedIndex or a loop to select the option by text, the code below doesn't work.

document.getElementById("mydropdown").text = 'Eggs';
Share:
53,758

Related videos on Youtube

Wooble
Author by

Wooble

Updated on July 31, 2020

Comments

  • Wooble
    Wooble over 3 years

    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?

  • Wooble
    Wooble over 12 years
    I don't want the text of the currently selected value; I want to set the value based on the text. Looping through el.options and looking for the right .text attribute looks promising, though.
  • SavoryBytes
    SavoryBytes over 12 years
    any reason you're using the children collection vs. dropdown.options and dropdown.options[i].text?
  • SavoryBytes
    SavoryBytes over 12 years
    yeah I think that's your best bet
  • Vismari
    Vismari over 12 years
    There is no specific reason, I just wrote that.
  • clarifier
    clarifier over 7 years
    for (var i = 0; i < ddlc.options.length; i++) { if (jQuery.trim(ddlc.options[i].text) == jQuery.trim(result)) { alert("Entered the needed"); var insertedtimeid = i $("#ddlCategory").val(insertedtimeid).trigger('updated').tri‌​gger('change'); break; } }

Related