Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
326 views
in Technique[技术] by (71.8m points)

javascript - 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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!");
});

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...