JQuery: detect change in input field [duplicate]
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.
Solution 1:
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/
Solution 2:
Use jquery change event
Description: Bind an event handler to the "change" JavaScript event, or trigger that event on an element.
An example
$("input[type='text']").change( function() {
// your code
});
The advantage that .change
has over .keypress
, .focus
, .blur
is that .change
event will fire only when input has changed