使用 JavaScript 获取下拉列表中选定的值
2009-07-06
5930106
如何使用 JavaScript 从下拉列表中获取选定的值?
<form>
<select id="ddlViewBy">
<option value="1">test1</option>
<option value="2" selected="selected">test2</option>
<option value="3">test3</option>
</select>
</form>
3个回答
给定一个如下所示的选择元素:
<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>
Paolo Bergantino
2009-07-06
纯 JavaScript:
var e = document.getElementById("elementId");
var value = e.options[e.selectedIndex].value;
var text = e.options[e.selectedIndex].text;
jQuery:
$("#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'
}];
Vitalii Fedorenko
2011-12-18
var strUser = e.options[e.selectedIndex].value;
这是正确的,应该会给出值。 这是你想要的文本吗?
var strUser = e.options[e.selectedIndex].text;
所以你清楚术语:
<select>
<option value="hello">Hello World</option>
</select>
此选项具有:
- Index = 0
- Value = hello
- Text = Hello World
Greg
2009-07-06