Can I open a dropdownlist using jQuery

2018-12-31 14:04发布

For this dropdownlist in HTML:

<select id="countries">
<option value="1">Country</option>
</select>

I would like to open the list (the same as left-clicking on it). Is this possible using JavaScript (or more specifically jQuery)?

14条回答
与风俱净
2楼-- · 2018-12-31 14:32

As has been stated, you can't programmatically open a <select> using JavaScript.

However, you could write your own <select> managing the entire look and feel yourself. Something like what you see for the autocomplete search terms on Google or Yahoo! or the Search for Location box at The Weather Network.

I found one for jQuery here. I have no idea whether it would meet your needs, but even if it doesn't completely meet your needs, it should be possible to modify it so it would open as the result of some other action or event. This one actually looks more promising.

查看更多
萌妹纸的霸气范
3楼-- · 2018-12-31 14:33

This should cover it:

 var event;
 event = document.createEvent('MouseEvents');
 event.initMouseEvent('mousedown', true, true, window);
 countries.dispatchEvent(event); //we use countries as it's referred to by ID - but this could be any JS element var

This could be bound for example to a keypress event, so when the element has focus the user can type and it will expand automatically...

--Context--

  modal.find("select").not("[readonly]").on("keypress", function(e) {

     if (e.keyCode == 13) {
         e.preventDefault();
         return false;
     }
     var event;
     event = document.createEvent('MouseEvents');
     event.initMouseEvent('mousedown', true, true, window);
     this.dispatchEvent(event);
 });
查看更多
登录 后发表回答