mpen
mpen

Reputation: 282865

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?

Upvotes: 10

Views: 7293

Answers (4)

Tim Down
Tim Down

Reputation: 324567

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

Upvotes: 24

Jason Miesionczek
Jason Miesionczek

Reputation: 14448

.change() is what you're after

$("#testbox").keyup(function() {
   $(this).blur();
   $(this).focus(); 
   $(this).val($(this).val()); // fix for IE putting cursor at beginning of input on focus
}).change(function() {
   alert("change fired");
});

Upvotes: 8

Jesse Aldridge
Jesse Aldridge

Reputation: 8149

This is how I would do it: http://jsfiddle.net/JesseAldridge/Pggpt/1/

$('#input1').keyup(function(){
    if($('#input1').val() != $('#input1').attr('prev_val'))
        $('#input2').val('change')
    else
        $('#input2').val('no change')
    $('#input1').attr('prev_val', $('#input1').val())
})

Upvotes: 2

Sam 山
Sam 山

Reputation: 42865

I came up with this for autosaving a textarea. It uses a combination of the .keyUp() jQuery method to see if the content has changed. And then I update every 5 seconds because I don't want the form getting submitted every time it's changed!!!!

var savePost = false;

jQuery(document).ready(function() { 
    setInterval('autoSave()', 5000)
    $('input, textarea').keyup(function(){
        if (!savePost) {
            savePost = true;    
        }
    })
})


function autoSave() {
    if (savePost) {
        savePost = false;
        $('#post_submit, #task_submit').click();            
    }
}

I know it will fire even if the content hasn't changed but it was easier that hardcoding which keys I didn't want it to work for.

Upvotes: 0

Related Questions