JavaScript:根据选项文本设置下拉列表选定项 [英] JavaScript: set dropdown selected item based on option text

查看:87
本文介绍了JavaScript:根据选项文本设置下拉列表选定项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

说我有这样的下拉列表:

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>

我希望根据选项文本设置所选值,而不是使用javascript设置值。我该怎么做呢?例如,使用c#我可以执行类似下面示例的操作,并选择带有Google的选项。

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

这篇关于JavaScript:根据选项文本设置下拉列表选定项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆