say I have a dropdown list like this:
<select id="MyDropDown">
<option value="0">Google</option>
<option value="1">Bing</option>
<option value="2">Yahoo</option>
</select>
and I want to set the selected value based on the option text, not the value with javascript. How can I go about doing this? For example, with c# I can do something like the example below and the the option with "Google" would be selected.
ListItem mt = MyDropDown.Items.FindByText("Google");
if (mt != null)
{
mt.Selected = true;
}
Thanks in advance for any help!
This question is related to
javascript
This works in latest Chrome, FireFox and Edge, but not IE11:
document.evaluate('//option[text()="Yahoo"]', document).iterateNext().selected = 'selected';
And if you want to ignore spaces around the title:
document.evaluate('//option[normalize-space(text())="Yahoo"]', document).iterateNext().selected = 'selected'
A modern alternative:
const textToFind = 'Google';
const dd = document.getElementById ('MyDropDown');
dd.selectedIndex = [...dd.options].findIndex (option => option.text === textToFind);
You can loop through the select_obj.options. There's a #text method in each of the option object, which you can use to compare to what you want and set the selectedIndex of the select_obj.
Source: Stackoverflow.com