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

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


当前回答

最简单的方法是:

var value = document.getElementById("selectId").value;

其他回答

最简单的方法是:

var value = document.getElementById("selectId").value;

运行示例:

var e=document.getElementById(“ddlViewBy”);var val1=e.options[e.selectedIndex].value;var txt=e.options[e.selectedIndex].text;document.write(“<br/>所选选项值:”+val1);document.write(“<br/>所选选项文本:”+txt);<select id=“ddlViewBy”><option value=“1”>test1</option><option value=“2”>test2</option><option value=“3”selected=“selected”>test3</option></选择>

注意:下拉列表更改时,值不会更改,如果您需要该功能,则需要执行onClick更改。

只需执行: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文本=你好世界

var selectedValue = document.getElementById("ddlViewBy").value;