<select id="users">
<option value="1">jack</option>
<option value="2">brill</option>
<option value="3">antony</option>
</select>
js:
$("#users").change(function(){
alert($(this).val());
})
why change event not fired when using (keyup/keydown) until mouse is clicked
why change event not fired when using (keyup/keydown) until mouse is clicked
It also fires when focus leaves the select
. That's just how the change
event works.
If you want proactive notification, you have to watch for change
and keydown
(at least, you may want click
as well) and handle the case of getting an event when the value hasn't actually changed, and you have to handle the fact that some of those events (keydown
, for instance) are fired before the value is changed, so you have to wait a moment before processing the event. Or see SpYk3HH's answer which uses keyup
instead — that will be less proactive (not updating until key release, which could be desireable), but then you don't need the delay (setTimeout
) my code below has.
Example (live copy):
HTML (I took the liberty of changing the values so it was clearer which went with each name):
<select id="users">
<option value="j">jack</option>
<option value="b">brill</option>
<option value="a">antony</option>
</select>
JavaScript:
$("#users").bind("keydown change", function(){
var box = $(this);
setTimeout(function() {
display(box.val());
}, 0);
});
Note in 2016: bind
has largely been replaced with on
. In the above it you'd literally just replace "bind" with "on".