如何使用JavaScript从下拉列表中获取所选值?

<表单><select id=“ddlViewBy”><option value=“1”>test1</option><option value=“2”selected=“selected”>test2</option><option value=“3”>test3</option></选择></form>


当前回答

如果您遇到过纯为Internet Explorer编写的代码,您可能会看到:

var e = document.getElementById("ddlViewBy");
var strUser = e.options(e.selectedIndex).value;

在Firefox等中运行上述命令会导致“不是函数”错误,因为Internet Explorer允许您使用()而不是[]:

var e = document.getElementById("ddlViewBy");
var strUser = e.options[e.selectedIndex].value;

正确的方法是使用方括号。

其他回答

onChange回调中的event.target.value为我提供了诀窍。

var strUser = e.options[e.selectedIndex].value;

这是正确的,应该为您提供值。是你想要的文本吗?

var strUser = e.options[e.selectedIndex].text;

所以你对术语很清楚:

<select>
    <option value="hello">Hello World</option>
</select>

此选项具有:

索引=0值=hello文本=你好世界

Try

ddlViewBy.value                      // value

ddlViewBy.selectedOptions[0].text    // label

console.log(ddlViewBy.value);console.log(ddlViewBy.selectedOptions[0].text);<select id=“ddlViewBy”><option value=“1”>快乐</option><option value=“2”>树</option><option value=“3”selected=“selected”>朋友</option></选择>

初学者可能希望使用NAME属性而不是ID属性访问select中的值。我们知道所有表单元素都需要名称,甚至在获得id之前。

因此,我将添加getElementsByName()解决方案,让新开发人员也能看到。

没有。表单元素的名称需要是唯一的,以便表单在发布后可以使用,但DOM可以允许多个元素共享名称。因此,如果可以,请考虑将ID添加到表单中,或者使用表单元素名称my_nth_select_named_x和my_nth_text_input_named_y显式添加ID。

使用getElementsByName的示例:

var e = document.getElementsByName("my_select_with_name_ddlViewBy")[0];
var strUser = e.options[e.selectedIndex].value;

只需执行:document.getElementById('dselect').options.selectedIndex

然后,您将获得从0开始的select索引值。