JavaScript: set dropdown selected item based on option text
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;
}
var textToFind = 'Google';
var dd = document.getElementById('MyDropDown');
for (var i = 0; i < dd.options.length; i++) {
if (dd.options[i].text === textToFind) {
dd.selectedIndex = i;
break;
}
}
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.
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'
精彩评论