如何使用 JavaScript 从下拉列表中获取选定的值?
我尝试了以下方法,但它们都返回选定的索引而不是值:
var e = document.getElementById("ddlViewBy"); function show(){ var as = document.forms[0].ddlViewBy.value; var strUser = e.options[e.selectedIndex].value; console.log(as, strUser); } e.onchange=show; show(); <form> <select id="ddlViewBy"> <option value="1">test1</option> <option value="2" selected="selected">test2</option> <option value="3">test3</option> </select> </form>
如果您有一个如下所示的选择元素:
<select id="ddlViewBy"> <option value="1">test1</option> <option value="2" selected="selected">test2</option> <option value="3">test3</option> </select>
运行此代码:
var e = document.getElementById("ddlViewBy"); var strUser = e.value;
会strUser成为2。如果您真正想要的是test2,请执行以下操作:
strUser
2
test2
var e = document.getElementById("ddlViewBy"); var strUser = e.options[e.selectedIndex].text;
这将strUser是test2