Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
634 views
in Technique[技术] by (71.8m points)

jquery - Need checkbox change event to respond to change of checked state done programmatically

(jQuery 1.4.4) I have a checkbox that has a .change() listener that works fine for when the user clicks the checkbox, but now I also need it to fire when I programmatically change the checkbox in jQuery, using .attr('checked', 'checked'). I'm perfectly happy to use other methods to make this work. Thanks.

$('#foo').attr('checked', 'checked'); // programmatically change the checkbox to checked, this checks the box alright

$('#foo').change( function() {
  // this works when user checks the box but not when the above code runs
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

If you're using jQuery > 1.6, you can do this quite smartly by defining a attrHook;

jQuery.attrHooks.checked = {
    set: function (el, value) {
        if (el.checked !== value) {
            el.checked = value;
            $(el).trigger('change');
        }
    }
};

As pointed out in the comments, the if avoids a change event triggering if the new value is the same as the old value.

... Although really you should be using prop() anyway, so it should be;

jQuery.propHooks.checked = {
    set: function (el, value) {
        if (el.checked !== value) {
            el.checked = value;
            $(el).trigger('change');
        }
    }
};

You can see this working here; http://jsfiddle.net/2nKPY/

For jQuery < 1.6 (or if you don't fancy adding a propHook) the best you can do is override the attr() method (or upgrade :));

(function () {
    var existingAttr = jQuery.fn.attr;

    jQuery.fn.attr = function (attr) {
        var result = existingAttr.apply(this, arguments);

        if (result instanceof jQuery && attr == "checked") { // If we're dealing with a check-set operation.
            result.trigger('change');
        }

        return this;
    };    

}());

You can see this in operation here


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...