Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

jquery

(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
}
like image 456
bethesdaboys Avatar asked Dec 05 '11 21:12

bethesdaboys


3 Answers

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

like image 58
Matt Avatar answered Oct 23 '22 06:10

Matt


How about:

$('some selector').trigger('click');
like image 29
ilivewithian Avatar answered Oct 23 '22 05:10

ilivewithian


Use jquery click() to change the state of the checkbox rather than changing its attribute.

Not having all your markup I'm not sure how suitable this would be, but I've used this method recently to good effect.

like image 34
Jamie Hartnoll Avatar answered Oct 23 '22 07:10

Jamie Hartnoll