views:

334

answers:

3

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>
+2  A: 

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

Gaby
A: 

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...

AlexV
Pressing enter to confirm a `<select>` element choice is a bad idea, it may submit a parent form as well as firing the `onchange` event.
Andy E
Unless you use a third world class Web browser or if the focus is NOT on the <select>, using enter is perfectly safe to confirm selection on a <select>. How do you think disabled people trigger onchange? By tabbing out and alt-tabbing back each time? Read WCAG or S508 guidelines for more info.
AlexV
A: 

it works if you change add attribue

multiple="multiple"

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

Kind Regards

--Andy

jAndy