I have a number input that should trigger jQuery on every change.
To do this, I do a $('#id').bind('keyup change', ...);, which is triggered on any keyup or mouse-controller changed.
This works find for mouse clicks (triggers change) and for typing numbers (triggers keyup). But for the cursor keys it triggers both change and keyup. How can I make it so it only triggers once in all situations?
Here’s an example showing the problem: http://jsfiddle.net/jSjkE/
You have a wrong concept about the
onchangeevent.It does NOT fire when the element’s value changes, instead, it fires only when 2 conditions are met:
Note: The above is for inputs of type
text. For typescheckbox/radioit fires as soon as theircheckedproperty changes, and forselectelements as soon as its selected option changes.The
onchangeevent (possibly wrongly) fires when you press Chrome’sinput type="number"up/down arrows. You should not rely on it, as many other major browsers don’t even have an implementation of the number inputs yet and may not follow this behavior.Instead, as you’re using HTML5, you should rely on the
oninputHTML5 event, which fires whenever the element’s value is updated.Fiddle
edit:
For older (and non-HTML5) browsers, you may use the
keyupevent as a fallback:The most resilient way to do this for non-HTML5 browsers would be having a
setIntervalconstantly checking if the element’s value has changed, askeyupdoes not trigger if you select some text and drag it into the textbox – you could try.on('input keyup mouseup', but then it wouldn’t trigger if the user uses the browser’s Edit > Paste menu.edit2:
If you don’t want to use
setInterval, you can put a huge events map inside the.on/.bindand check if the value has changed by storing the current value in the.data()of the element:Fiddle
I’ve added the
onchangeevent to the events map, so even if theoninputandonkeyupfails (non-html5 browser using the browser’s menu to paste data), theonchangeevent will still fire when the element loses focus.Here’s the final edit with a commented
setIntervaland.data()to avoid using globals, so you can choose which of the fallbacks to use:Fiddle