简体   繁体   中英

Selecting an item in an HTML SELECT list using keyboard doesnt trigger the CLICK event

I have an HTML select list which, when an item is selected, must show different information beneath it. The onclick or JQuery change events are triggered when a select list item is selected by being clicked on (mouse), but not when the user uses key presses (keyboard).

Any idea what event to watch in order to determine when the selected list item has changed?

Here is a BASIC test example:

<select id="mylist" name="mylist">
    <option value="">(none)</option>
    <option value="1">Test 1</option>
    <option value="2">Test 2</option>
    <option value="3">Test 3</option>
</select>

<span id="myspan"></span>

<script type="text/javascript">
    $("#mylist").change(function() {
        $("#myspan").html($("#mylist").attr("selectedIndex"));
    });
</script>

The code will run when the select box loses focus
( press tab or click anywhere outside of the select box )

The OnChange event is different from browser to browser when an item is changed with keyboard shortcuts.

For example, in IE, the event is fired the same way with the keyboard and the mouse, but in Firefox, to trigger the event with the keyboard, you need to press enter when the item selected is the good one. The event is also fired when the <select> loose focus (OnBlur - and only if OnChange has not already been fired) as Gaby pointed out.

It the way it's made...

It works if you change add attribute:

multiple="multiple"

if you want the dropbox, I'd bind a 'global' keyup event handler to the document.body and do some magic there.

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