JQuery: detect change in input field

CL22 picture CL22 · Oct 9, 2012 · Viewed 414.4k times · Source

I want to detect when a user's keyboard actions alter the value of a text field. It should work consistently across modern browsers.

The JQuery page for the .keypress event says it's not consistent? Also, it doesn't work for backspace, delete etc.

I can't use .keydown as it is because it reacts to shift, alt and arrow keys etc. Also, it doesn't fire more than once when the user holds down a key and multiple characters are inserted.

Is there a concise method I'm missing? Or should I use .keydown and filter out events that are triggered by arrow keys, shift and so on? My main concern is there will be keys that I'm not aware should be filtered. (I nearly forgot about alt and ctrl, I suppose there could be others) But then how would I detect the key being held down and inserting multiple characters?

As a bonus it would detect changes due to pasting (including right-clicking) but I have the solution to that from here.

Answer

Timm picture Timm · Oct 9, 2012

You can bind the 'input' event to the textbox. This would fire every time the input changes, so when you paste something (even with right click), delete and type anything.

$('#myTextbox').on('input', function() {
    // do something
});

If you use the change handler, this will only fire after the user deselects the input box, which may not be what you want.

There is an example of both here: http://jsfiddle.net/6bSX6/