如何使用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>
当前回答
只需使用
$('#SelectBoxId选项:selected').text();获取列出的文本$('#SelectBoxId').val();用于获取所选索引值
其他回答
Use:
<select id="Ultra" onchange="alert(this.value)">
<option value="0">Select</option>
<option value="8">text1</option>
<option value="5">text2</option>
<option value="4">text3</option>
</select>
从元素内部访问任何输入/表单字段时,都可以使用“this”关键字。这样就不需要在DOM树中查找表单,然后在表单中查找该元素。
onChange回调中的event.target.value为我提供了诀窍。
如果您遇到过纯为Internet Explorer编写的代码,您可能会看到:
var e = document.getElementById("ddlViewBy");
var strUser = e.options(e.selectedIndex).value;
在Firefox等中运行上述命令会导致“不是函数”错误,因为Internet Explorer允许您使用()而不是[]:
var e = document.getElementById("ddlViewBy");
var strUser = e.options[e.selectedIndex].value;
正确的方法是使用方括号。
另一种解决方案是:
document.getElementById('elementId').selectedOptions[0].value
2015年,在Firefox中,以下功能同样有效。
e.options.selected索引