views:

3167

answers:

6

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 :-)

A: 

You could use the keydown, keyup and keypress events as well.

Gumbo
+14  A: 

So, you want the onchange event to fire on keydown, blur, and paste? That's magic.

If you want to track changes as they type, use "onkeydown". If you need to trap paste operations with the mouse, use "onpaste" (IE, FF3) and "oninput" (FF, Opera, Chrome, Safari1).

1Broken for <textarea> on Safari. Use textInput instead

Crescent Fresh
Great, oninput also works in Opera, thanks!
Ilya Birman
And it also works in Safari!
Ilya Birman
Haven’t you checked oninput in IE (Don’t have it on a Mac)? Because checking for paste itself is not enough: you can select and cut, for example. Thanks.
Ilya Birman
Looks like oninput does not work on textarea in Safari...
Ilya Birman
+1 very nice quick reference! thanks
curtisk
A: 

I had a similar requirement (twitter style text field). Used 'onkeyup' and 'onchange'. onchange actually takes care of mouse paste operations during lost focus from the field.

A: 

onkeyup happens after you type for example I press "t" when I lift the finger the action happens but on keydown the action happens before I digit the character "t"

Hope this is helpfull for someone.

So onkeyup is better for when you whant to send what you just typed NOW.

netcrash
+1  A: 

If you use ONLY Internet Explorer, you can use this:

<input type="text" id="myID" onpropertychange="TextChange(this)" />

<script type="text/javascript">
    function TextChange(tBox) {
        if(event.propertyName=='value') {
            //your code here
        }
    }
</script>

Hope that helps.

RolandDeschain
A: 

However I've tried this, but what if the user types in a unicode character using ALT+NUM, the event does not detect the text change until the user either triggers the event with another character input

How should we go about tracking text change when user enters ALT+Num character?

jenn