jQuery 从javascript函数打开下拉列表
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19652085/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
open dropdown list from javascript function
提问by Subodh
Iam trying to show the dropdown option when javascript function is called. but eventually iam not succeed on this. need help Here is my code:
我试图在调用 javascript 函数时显示下拉选项。但最终我没有成功。需要帮助这是我的代码:
<script>
function showState(str){
$('#Acntname').trigger('click');
}
</script>
...
<select class="input_panel" id="Acntname" >
<option value="0">Select</option>
<option value="1">Equity Share Capital</option>
<option value="2">Deprication Fund</option> </select>
<input type="text" class="input_panel" id="accountname" onkeyup="showState(this.value)"/>
i used triggered function to open the dropdown but it doesn't work.
我使用触发功能打开下拉菜单,但它不起作用。
回答by nik
Here you go..you can do this by dispatching mousedown event on dropdown..
给你..你可以通过在下拉菜单上调度 mousedown 事件来做到这一点..
JS:
JS:
window.showState = function (str) {
var dropdown = document.getElementById('Acntname');
var event = document.createEvent('MouseEvents');
event.initMouseEvent('mousedown', true, true, window);
dropdown.dispatchEvent(event);
}
EDIT: This works perfectly in Chrome <53, not sure for Firefox and IE.
编辑:这在Chrome <53 中完美运行,不确定是否适用于 Firefox 和 IE。
回答by Peter Munnings
You can do this:
你可以这样做:
var sel = document.getElementById('Acntname');
var len = sel.options.length;
sel.setAttribute('size', len);
Set the size back to 1 to close it
将大小设置回 1 以关闭它
回答by Ricky Stam
You can't open the dropdown list but there is a semi-solutionyou could do the following
您无法打开下拉列表,但有一个半解决方案您可以执行以下操作
to "open" the list:
“打开”列表:
$("#Acntname").attr("size","3");
and
和
$("#Acntname").attr("size","1");
to close the list.
关闭列表。
回答by Rohan Kumar
Its not possible to toggle
the drop down
on triggering other element
.
它不可能toggle
在drop down
上triggering other element
。
If you want to select the value of select box
on keyup event
of textbox
then try this,
如果你想选择select box
on keyup event
of的值,textbox
那么试试这个,
function showState(str){
// alert(str);
$('#Acntname option[value="'+str+'"]').prop('selected',true);
}