3

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)?

Tim
  • 8,669
  • 31
  • 105
  • 183
  • As of jQuery 1.7, the `.live()` method is deprecated. Use `.on()`  to attach event handlers. Users of older versions of jQuery should use `.delegate()`  in preference to `.live()`. – ROY Finley Jan 24 '13 at 19:20
  • Interaction events aren't automatically triggered when you modify properties/attributes, you'll have to trigger them yourself. – Kevin B Jan 24 '13 at 19:22
  • @KevinB: thanks for the info re interaction events. – Tim Jan 24 '13 at 19:53
  • @ROY Finley: appreciate the heads up; have changed it to on(). – Tim Jan 24 '13 at 19:54

3 Answers3

2

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.

Joseph Silber
  • 214,931
  • 59
  • 362
  • 292
1

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.

Matthew Walker
  • 2,527
  • 3
  • 24
  • 30
0

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()

makki
  • 2,097
  • 3
  • 23
  • 34
  • thanks for the jsFiddle example. Here's a challenge: what if we say that the ALL checkbox cannot remain checked if one of the other checkboxes become unchecked by the user. – Tim Jan 24 '13 at 20:32