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';
Related videos on Youtube
Author by
Wooble
Updated on July 31, 2020Comments
-
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 over 12 yearsI 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 over 12 yearsany reason you're using the children collection vs. dropdown.options and dropdown.options[i].text?
-
SavoryBytes over 12 yearsyeah I think that's your best bet
-
Vismari over 12 yearsThere is no specific reason, I just wrote that.
-
clarifier over 7 yearsfor (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').trigger('change'); break; } }