I need to check for all events which will change the contents of my text input. so far I have handlers for keyup, cut and paste. but the content can also be changed by highlighting the text and clicking delete or undo. is there a way to listen for these events?
$('#input').on('paste cut keyup ',function() {
//add delete and undo to listner
});
You have more problems than this, you also have to worry about browsers with autofill features, etc. For this reason HTML5 has included the input
event, which is included in modern browsers.
See this answer for a method of capturing every conceivable change event(*) the browser will let you capture, without firing more than once per change.
(*) Looks like they forgot cut
, so add that in too.
I'd suggest using keydown
and input
: http://jsfiddle.net/vKRDR/
var timer;
$("#input").on("keydown input", function(){
var self = this;
clearTimeout(timer)
// prevent event from happening twice
timer = setTimeout(function(){
console.log(self.value);
},0);
});
keyup won't catch special keys such as ctrl, and input will catch things such as paste delete etc, even from context menu.
by using keydown and input, the event happens immediately rather than waiting for the user to release the button or blur the input.
keydown does most of the work, input picks up where keydown can't handle it such as the context menu delete/paste/cut
use these, they will get all the changes :
$(container).bind('keyup input propertychange paste change'), function (e){});
also, you could do one thing to check the value inside this onchange event:
$(function(){
$('input').on('keyup input propertychange paste change', function(){
if ($(this).data('val')!=this.value) {
alert('Something has been changed in the input.');
}
$(this).data('val', this.value);
});
});
hopefully, this will work in your case. :)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With