如何使用JavaScript从下拉列表中获取所选值?
<表单><select id=“ddlViewBy”><option value=“1”>test1</option><option value=“2”selected=“selected”>test2</option><option value=“3”>test3</option></选择></form>
如何使用JavaScript从下拉列表中获取所选值?
<表单><select id=“ddlViewBy”><option value=“1”>test1</option><option value=“2”selected=“selected”>test2</option><option value=“3”>test3</option></选择></form>
当前回答
纯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
角度JS:(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'
}];
其他回答
另一种解决方案是:
document.getElementById('elementId').selectedOptions[0].value
onChange回调中的event.target.value为我提供了诀窍。
下面的代码展示了使用JavaScript从输入/选择字段获取/放置值的各种示例。
源链接
使用Javascript和jQuery演示
<select id="Ultra" onchange="run()"> <!--Call run() function-->
<option value="0">Select</option>
<option value="8">text1</option>
<option value="5">text2</option>
<option value="4">text3</option>
</select><br><br>
TextBox1<br>
<input type="text" id="srt" placeholder="get value on option select"><br>
TextBox2<br>
<input type="text" id="rtt" placeholder="Write Something !" onkeyup="up()">
以下脚本获取所选选项的值并将其放入文本框1
<script>
function run() {
document.getElementById("srt").value = document.getElementById("Ultra").value;
}
</script>
下面的脚本从文本框2中获取一个值,并用其值发出警报
<script>
function up() {
//if (document.getElementById("srt").value != "") {
var dop = document.getElementById("srt").value;
//}
alert(dop);
}
</script>
以下脚本正在从函数调用函数
<script>
function up() {
var dop = document.getElementById("srt").value;
pop(dop); // Calling function pop
}
function pop(val) {
alert(val);
}?
</script>
只需使用
$('#SelectBoxId选项:selected').text();获取列出的文本$('#SelectBoxId').val();用于获取所选索引值
2015年,在Firefox中,以下功能同样有效。
e.options.selected索引