如何使用Javascript通过选项的值在选择框中选择一个选项? [英] How to select an option in a select box by the value of the option using Javascript?

查看:76
本文介绍了如何使用Javascript通过选项的值在选择框中选择一个选项?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个选择框,其中填充了它可以拥有的所有可用选项。当用户单击我的应用程序中的记录时,我会得到一个xml响应,其中包含该记录的选项值。我想使用javascript在选择框中为该特定选项设置所选索引,而无需重新加载选择框。是否有一种简单的方法可以根据选项的值或名称查找选项的索引?然后,我可以将该选项设置为选定的索引。

I have a select box that is populated with all the available options it can have. When a user clicks on a record in my application, I get an xml response that includes the value of the option for that record. I'd like to use javascript to set the selected index for that particular option in the select box without having to reload the select box. Is there an easy way to find the index of an option based on the value or name of the option? Then, I could set that option as the selected index.

推荐答案

我是第二个托比的回答。但是,如果由于某种原因你不能使用现有的库,那么在简单的javascript中就可以轻松完成:

I'd second Toby's answer. Still, if you can't use an existing library for some reason, it's easy enough to do in plain javascript:

function selectByValue(el, value) {
    for (var i=0, len=options.length; i<len; i++) {
        if (el.options[i].value == value) {
            el.selectedIndex = i;
            break;
        }
    }
}

如果您愿意请改用该选项的文本,将 .value 替换为 .text 。我假设您的意思是文本,因为选择选项没有名称属性。

If you'd like to use the text of the option instead, replace .value with .text. I assume you meant "text" since select options don't have a "name" property.

这篇关于如何使用Javascript通过选项的值在选择框中选择一个选项?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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