Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Catch only keypresses that change input?

I want to do something when a keypress changes the input of a textbox. I figure the keypress event would be best for this, but how do I know if it caused a change? I need to filter out things like pressing the arrow keys, or modifiers... I don't think hardcoding all the values is the best approach.

So how should I do it?

like image 201
mpen Avatar asked Jun 27 '11 02:06

mpen


People also ask

How do you find the change field input?

Answer: Use the input Event You can bind the input event to an input text box using on() method to detect any change in it. The following example will display the entered value when you type something inside the input field.

What is the difference between keypress and keydown?

The keydown and keyup events provide a code indicating which key is pressed, while keypress indicates which character was entered. For example, a lowercase "a" will be reported as 65 by keydown and keyup , but as 97 by keypress .

What is keyup and keydown?

KeyDown occurs when the user presses a key. KeyUp occurs when the user releases a key.

What is onkeypress?

Definition and Usage. The onkeypress attribute fires when the user presses a key (on the keyboard). Tip: The order of events related to the onkeypress event: onkeydown. onkeypress.


1 Answers

In most browsers, you can use the HTML5 input event for text-type <input> elements:

$("#testbox").on("input", function() {
    alert("Value changed!");
});

This doesn't work in IE < 9, but there is a workaround: the propertychange event.

$("#testbox").on("propertychange", function(e) {
    if (e.originalEvent.propertyName == "value") {
        alert("Value changed!");
    }
});

IE 9 supports both, so in that browser it's better to prefer the standards-based input event. This conveniently fires first, so we can remove the handler for propertychange the first time input fires.

Putting it all together (jsFiddle):

var propertyChangeUnbound = false;
$("#testbox").on("propertychange", function(e) {
    if (e.originalEvent.propertyName == "value") {
        alert("Value changed!");
    }
});

$("#testbox").on("input", function() {
    if (!propertyChangeUnbound) {
        $("#testbox").unbind("propertychange");
        propertyChangeUnbound = true;
    }
    alert("Value changed!");
});
like image 69
Tim Down Avatar answered Sep 27 '22 20:09

Tim Down