Reputation: 233
I'm looking for a (jQuery) Event Handler that is executing a function immediately after a input[type="text"]
value changed. The .change
jQuery event handler is executing the function after the input[type="text"]
looses focus (which may be good for another situation).
keypress
/ up
/ down
only work when the user types something into an input (not when I'm manipulating it dynamically).
Is there any solution for this?
Upvotes: 6
Views: 6588
Reputation: 8402
First, I would modify the JQuery change event to fire even when you change it dynamically with the val
function. It really doesn't make sense to me why this is not the default behavior in JQuery. Here is the code to do this:
//Store the old val function
$.fn.custom_oldVal = $.fn.val;
//Update the val function to fire the change event where appropriate:
$.fn.val = function(value) {
if(value == null || value == undefined){
return this.custom_oldVal();
} else {
//Only call onchange if the value has changed
if(value == this.custom_oldVal()){
return this;//Return this object for chain processing
} else {
return this.custom_oldVal(value).change();
}
}
}
If you need it to fire at other times, add those event listeners as well, following the procedure mentioned by jimbojw.
Upvotes: 3
Reputation: 11042
One thing that I do in cases like this is to bind the same handler to a bunch of events.
$('input').bind("change blur keyup mouseup", function() {
$(this).css("color", "red"); // or whatever you want to happen
});
See http://api.jquery.com/bind/
Upvotes: 11