In my experience, input type="text"
onchange
event usually occurs only after you leave (blur
) the control.
Is there a way to force browser to trigger onchange
every time textfield
content changes? If not, what is the most elegant way to track this “manually”?
Using onkey*
events is not reliable, since you can right-click the field and choose Paste, and this will change the field without any keyboard input.
Is setTimeout
the only way?.. Ugly :-)
Javascript is unpredictable and funny here.
onchange
occurs only when you blur the textboxonkeyup
&onkeypress
doesn't always occur on text changeonkeydown
occurs on text change (but cannot track cut & paste with mouse click)onpaste
&oncut
occurs with keypress and even with the mouse right click.So, to track the change in textbox, we need
onkeydown
,oncut
andonpaste
. In the callback of these event, if you check the value of the textbox then you don't get the updated value as the value is changed after the callback. So a solution for this is to set a timeout function with a timeout of 50 mili-seconds (or may be less) to track the change.This is a dirty hack but this is the only way, as I researched.
Here is an example. http://jsfiddle.net/2BfGC/12/
I had a similar requirement (twitter style text field). Used
onkeyup
andonchange
.onchange
actually takes care of mouse paste operations during lost focus from the field.[Update] In HTML5 or later, use
oninput
to get real time character modification updates, as explained in other answers above.These days listen for
oninput
. It feels likeonchange
without the need to lose focus on the element. It is HTML5.It’s supported by everyone (even mobile), except IE8 and below. For IE add
onpropertychange
. I use it like this:I think in 2018 it's better to use the
input
event.-
As the WHATWG Spec describes (https://html.spec.whatwg.org/multipage/indices.html#event-input-input):
-
Here's an example of how to use it:
If you use ONLY Internet Explorer, you can use this:
Hope that helps.
there is a quite near solution (do not fix all Paste ways) but most of them:
It works for inputs as well as for textareas:
Do like this:
As i said, not all ways to Paste fire an event on all browsers... worst some do not fire any event at all, but Timers are horrible to be used for such.
But most of Paste ways are done with keyboard and/or mouse, so normally an onkeyup or onmouseup are fired after a paste, also onkeyup is fired when typing on keyboard.
Ensure yor check code does not take much time... otherwise user get a poor impresion.
Yes, the trick is to fire on key and on mouse... but beware both can be fired, so take in mind such!!!