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

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


当前回答

2015年,在Firefox中,以下功能同样有效。

e.options.selected索引

其他回答

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

Use:

<select id="Ultra" onchange="alert(this.value)">
    <option value="0">Select</option>
    <option value="8">text1</option>
    <option value="5">text2</option>
    <option value="4">text3</option>
</select>

从元素内部访问任何输入/表单字段时,都可以使用“this”关键字。这样就不需要在DOM树中查找表单,然后在表单中查找该元素。

2015年,在Firefox中,以下功能同样有效。

e.options.selected索引

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

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

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

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

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

所以你对术语很清楚:

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

此选项具有:

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