本文介绍了使用JavaScript在下拉列表中获取选定的值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何使用JavaScript从下拉列表中获取所选值?
How do I get the selected value from a dropdown list using JavaScript?
我尝试了以下方法,但它们都返回所选索引而不是值:
I tried the methods below but they all return the selected index instead of the value:
var as = document.form1.ddlViewBy.value;
var e = document.getElementById("ddlViewBy");
var strUser = e.options[e.selectedIndex].value;
var value = document.getElementById("ddlViewBy").value;
推荐答案
如果你有一个如下所示的select元素:
If you have a select element that looks like this:
<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.options[e.selectedIndex].value;
将 strUser
设为 2
。如果您真正想要的是 test2
,那么请执行以下操作:
Would make strUser
be 2
. If what you actually want is test2
, then do this:
var e = document.getElementById("ddlViewBy");
var strUser = e.options[e.selectedIndex].text;
这将使 strUser
为 test2
这篇关于使用JavaScript在下拉列表中获取选定的值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!