简体   繁体   中英

How to use javascript or jquery to get keyboard input when html drop down menu is show?

I want to get the input using javascript or jquery when user press the keyboard. It is possible when the drop down menu is not show. When the drop down menu is show, onkeypress will not be fired.

<html>
<body>
<select id="test" onkeypress="sayHello()">
<option value="1">1234</option>
<option value="5">5678</option>
</select>
</body>

<script>
function sayHello(){
    alert("Hello");
}
</script>
</html>

I think this is not possible with the default select-dropdown, because the opened dropdown-menu is created on top of the browser window and not actually part of the document.

You could use/build some kind of replacement that renders a custom dropdown menu with html-elements inside the document and then capture all the events you want.

For example take a look at Select2 . But there are also plenty other libraries.

Here is an example that uses select2 and only alerts if a keydown-event happens and the dropdown is open:

 $(document).ready(function() { $('#example').select2({ minimumResultsForSearch: 99 }); let isDropdownOpen = false; $('#example').on('select2:open', function(event) { isDropdownOpen = true; }); $('#example').on('select2:close', function(event) { isDropdownOpen = false; }); $(document).on('keydown', function(event) { if (isDropdownOpen) { event.preventDefault(); alert('Hello!'); } }); }); 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.7/css/select2.min.css" rel="stylesheet" /> <script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.7/js/select2.min.js"></script> <select id="example" name="example"> <option value="1234">1234</option> <option value="5678">5678</option> </select> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM