JQuery live and maintain and modify

I need to fire an event when the "checked" state of any of several checkboxes is changed, and there is no click listening for that. Why?

It looks like this:

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

      

When you click the All Flavors button, all other checkboxes are checked for testing:

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

      

The function works on the visible image - all the checkboxes are checked. However, if I listen to the state change like this:

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

      

the DispenseFlavor () method is only called if I physically click on that checkbox, not if the checked state is changed by setting the checked property to true, as it does in the checkAllFlavors () function.

Is a checkbox change changed only through GUI interaction and not through setting a property with $(elem).prop('checked', true)

?

+3


source to share


3 answers


You need to manually fire the event change

from your function checkAllFlavors

:

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

      



By the way, you must cache this selector.

+2


source


I found this answer from on 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 checked change handler with the prop method. This handler fires the change event as desired, but without having to manually specify it.

+1


source


Have a look at an example at http://jsfiddle.net/nGQKw/7/ , hoping it solves your problem. Actually you need an trigger

change

event for the checkboxes manually incheckAllFlavors()

0


source







All Articles