Reputation: 2577
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
});
Upvotes: 9
Views: 23486
Reputation: 11
Use this to detect deleting action on input value
document.getElementById("my_id_name").oninput = function(e) {
if ((e.inputType == 'deleteContentBackward') || (e.inputType == 'deleteContentForward') || (e.inputType == 'deleteByCut')){
$('my_id_name').value = null
})
}
Upvotes: 1
Reputation: 29
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. :)
Upvotes: 1
Reputation: 11461
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.
Upvotes: 9
Reputation: 95062
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
Upvotes: 2
Reputation: 116
You're at least missing keypress and change. I don't know if "change" works with those actions, I do know that change is often just called when the input element loses focus.
Upvotes: 0