I have a popup menu similar to this:
<select id="test"> <option value="1">1</option> <option value="2">2</option> <option value="3">3</option> <option value="4">4</option> </select>
If I want to start something when the user changes his choice, it is easy with jQuery .change() . However, it is well known that this will not work if the user has <select> active and simply moves through the options using the up / down arrows (or other keyboard navigation methods).
This is a problem for my use case. I need an event to fire based on the selected value, even if the up / down arrows are used to view various parameters.
I am not the first person to have this problem. This question is discussed here , which basically says that you need to look for keystrokes if you want to handle this script in all browsers. Other similar questions here have similar answers. But ... this does not work, as I will illustrate below.
Apparently, the easiest way to fix this is to use jQuery .keypress() to notice when <select> active and the key is pressed. Something like that:
<select id="test"> <option value="1">1</option> <option value="2">2</option> <option value="3">3</option> <option value="4">4</option> </select> <div id="log"> <script> var log = $("#log"); var select = $("#test"); select.change(function () { log.append(select.val() + "<br>"); }); select.keypress(function () { log.append(select.val() + "<br>");; }); </script>
You can try it here.
I tested this on Chrome 25 (Ubuntu 12.10 and Windows XP), Firefox 19 (Ubuntu 12.10) and IE 7 (Windows XP), which are the only browsers I have on hand.
My code works fine in all but Firefox. In my example, double-click the drop-down menu to select it with the menu closed, then click “down”, “down”, “down” (go to 2, 3 and 4) and “up, up, up” (go to 3, 2 and 1), and you will see this conclusion:
2 3 4 3 2 1
Great, perfect. But in Firefox does the same:
1 2 3 4 3 2
He is behind one record. The displayed value is the previous, not the current. This is problem.
Any ideas how to fix this?