最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - jQuery Event Handler for immediate changes in inputs - Stack Overflow

programmeradmin3浏览0评论

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?

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?

Share Improve this question edited Feb 11, 2016 at 0:26 rodorgas 1,0922 gold badges13 silver badges32 bronze badges asked May 12, 2011 at 19:01 iWebiWeb 2331 gold badge3 silver badges8 bronze badges 3
  • What type of input is it? type=text? Which browser(s) do you plan to support? – jimbo Commented May 12, 2011 at 19:07
  • Yep. input[type="text"] (It'd be even more awesome with type="range" etc but text is enough). And basically every modern browser (not IE6). – iWeb Commented May 12, 2011 at 19:10
  • when I'm manipulating it dynamically what do you mean with that? When you change the value using .val() ? – Felix Kling Commented May 12, 2011 at 19:25
Add a ment  | 

2 Answers 2

Reset to default 11

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./bind/

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.

发布评论

评论列表(0)

  1. 暂无评论