如何使用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或jQuery完成此操作。
JavaScript:
var getValue = document.getElementById('ddlViewBy').selectedOptions[0].value;
alert (getValue); // This will output the value selected.
OR
var ddlViewBy = document.getElementById('ddlViewBy');
var value = ddlViewBy.options[ddlViewBy.selectedIndex].value;
var text = ddlViewBy.options[ddlViewBy.selectedIndex].text;
alert (value); // This will output the value selected
alert (text); // This will output the text of the value selected
jQuery:
$("#ddlViewBy:selected").text(); // Text of the selected value
$("#ddlViewBy").val(); // Outputs the value of the ID in 'ddlViewBy'
其他回答
在onchange函数中有一个简单的方法:
event.target.options[event.targets.selectedIndex].dataset-name
var selectedValue = document.getElementById("ddlViewBy").value;
有一个解决方法,使用EasyUI框架及其所有插件。
您只需要在下拉菜单中添加一些EasyUI对象,该对象可以作为“桥”从输入中读取。
示例:easyui搜索框
左边是下拉列表,右边是easyui搜索框:
...
<input id="ss" class="easyui-searchbox" style="width:300px"
data-options=" searcher:my_function,
prompt:'Enter value',
menu:'#mm'">
<div id="mm" style="width:200px">
<div data-options="name:'1'">test1</div>
<div data-options="name:'2'">test2</div>
</div>
...
...
<script type="text/javascript">
function my_js_function(triggeredByButton = false){
// normal text of the searchbox (what you entered)
var value = $("#ss").searchbox("getValue");
// what you chose from the drop-down menu
var name = $("#ss").searchbox("getName");
...
注意:var名称是“1”或“2”,即“下拉列表的值”,而var值是在easyui搜索框中输入的值,如果您只想知道下拉列表的数值,则不相关。
我检查了EasyUI如何获取这个#mm名称,如果没有EasyUI的帮助,我无法找到如何获取这个名称。getName后面的jQuery:
getName:function(jq){
return $.data(jq[0],"searchbox").searchbox.find("input.textbox-value").attr("name");
}
注意,此函数的返回不是easyui搜索框的值,而是用作easyui查询框菜单参数的#mm下拉列表的名称。不知何故,EasyUI必须获得其他值,因此它必须是可能的。
如果您不想看到任何插件,请尽可能缩小它?或者在上面的链接中找到一个根本不需要表单的插件,我只是没有花时间。
给定如下所示的select元素:
<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”);函数onChange(){var值=e.value;var text=e.options[e.selectedIndex].text;console.log(值,文本);}e.onchange=onchange;onChange();<表单><select id=“ddlViewBy”><option value=“1”>test1</option><option value=“2”selected=“selected”>test2</option><option value=“3”>test3</option></选择></form>
onChange回调中的event.target.value为我提供了诀窍。