Question

I need to fire an event when the 'checked' state of any one of several checkboxes is changed, and to do this not by listening for the click. Why?

It looks like this:

    BUILD YOUR SUNDAE!
    All Flavors []     Chocolate [ ]   Vanilla [ ] Strawberry [ ]  Pistacchio [ ]

When All Flavors is clicked, all of the other checkboxes are set to be checked:

function checkAllFlavors() {
   $("#flavorFilterContainer input.flavor-filter").each(function (i, elem) {
       $(elem).prop('checked', true);
   });
 }

The function above visibly works -- all of the checkboxes are checked. However, if I listen for state-change like this:

      ("#flavorFilterContainer input.flavor-filter").live('change', function () {
           DispenseFlavor()
      });

the DispenseFlavor() method is invoked only if I physically click on a checkbox, not if the checkbox's checked state is changed by setting the checked property to true as occurs in the checkAllFlavors() function.

Is the checkbox's changed state altered only by GUI interaction and not via the setting of the property with $(elem).prop('checked', true)?

Was it helpful?

Solution

You'll have to manually fire the change event from within your checkAllFlavors function:

function checkAllFlavors () {
   $('#flavorFilterContainer input.flavor-filter').prop('checked', true).change();
}

BTW, you should cache that selector.

OTHER TIPS

I found this answer from the jQuery forums:

$.propHooks.checked = {
  set: function(elem, value, name) {
    var ret = (elem[ name ] = value);
    $(elem).trigger("change");
    return ret;
  }
};

This solution is a custom handler for changes to 'checked' via the 'prop' method. This handler triggers a change event as desired, but without you having to specify it manually.

Check example on http://jsfiddle.net/nGQKw/7/ hope it will solve your problem. Actually you have to trigger change event for the checkboxes manually in the checkAllFlavors()

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top