.jpg)
如何使用 JavaScript 从下拉列表中获取所选值?
<form>
<select id="ddlViewBy">
<option value="1">test1</option>
<option value="2" selected="selected">test2</option>
<option value="3">test3</option>
</select>
</form>

网友回答:
普通的JavaScript:
var e = document.getElementById("elementId");
var value = e.options[e.selectedIndex].value;
var text = e.options[e.selectedIndex].text;
j查询:
$("#elementId :selected").text(); // The text content of the selected option
$("#elementId").val(); // The value of the selected option
AngularJS: (http://jsfiddle.net/qk5wwyct):
// HTML
<select ng-model="selectItem" ng-options="item as item.text for item in items">
</select>
<p>Text: {{selectItem.text}}</p>
<p>Value: {{selectItem.value}}</p>
// JavaScript
$scope.items = [{
value: 'item_1_id',
text: 'Item 1'
}, {
value: 'item_2_id',
text: 'Item 2'
}];

网友回答:
给定一个如下所示的选择元素:
<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 value = e.value;
var text = e.options[e.selectedIndex].text;
结果:
value == 2
text == "test2"
交互式示例:
var e = document.getElementById("ddlViewBy");
function onChange() {
var value = e.value;
var text = e.options[e.selectedIndex].text;
console.log(value, text);
}
e.onchange = onChange;
onChange();
<form>
<select id="ddlViewBy">
<option value="1">test1</option>
<option value="2" selected="selected">test2</option>
<option value="3">test3</option>
</select>
</form>

网友回答:
var strUser = e.options[e.selectedIndex].value;
这是正确的,应该给你价值。
是你想要的文本吗?
var strUser = e.options[e.selectedIndex].text;
所以你很清楚术语:
<select>
<option value="hello">Hello World</option>
</select>
此选项具有:
模板简介:该模板名称为【使用 JavaScript 获取下拉列表中的选定值】,大小是暂无信息,文档格式为.编程语言,推荐使用Sublime/Dreamweaver/HBuilder打开,作品中的图片,文字等数据均可修改,图片请在作品中选中图片替换即可,文字修改直接点击文字修改即可,您也可以新增或修改作品中的内容,该模板来自用户分享,如有侵权行为请联系网站客服处理。欢迎来懒人模板【JavaScript】栏目查找您需要的精美模板。