使用 JavaScript 获取下拉列表中的选定值 [英] Get selected value in dropdown list using JavaScript
本文介绍了使用 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 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 元素:
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.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 获取下拉列表中的选定值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文