11
<li>
 <input type="checkbox" id="master" />
   <ul>
   <li>
     <input type="checkbox" />

$('input').bind('change', function() {}); // exists elsewhere, cannot change

When I click the top level input, I want to set .prop('checked', true) for all of its children, but I want to avoid triggering the change event for each child checkbox.

How could I set .prop('checked', true) to an input without triggering change?

Edit: (expanding)

$('#master').click(function() {
    $(this).parent().find('input').each(function(n, in) {
        $(in).prop('checked', true); // this triggers a change event that I need to stop
    });
});
tester
  • 22,441
  • 25
  • 88
  • 128

3 Answers3

22

What you are describing is the default functionality. Changing an element from javascript does not fire the change event.

http://jsfiddle.net/8JsP4/

Notice how if you click on a checkbox in the example, you get an alert, but if you click the button, no alert.

James Montagne
  • 77,516
  • 14
  • 110
  • 130
  • I think to recreate my symptom, you'd have to use an upper level checkbox to check all of the lower level boxes instead of a separate button – tester Feb 03 '12 at 21:58
  • 1
    Still not a problem http://jsfiddle.net/8JsP4/1/ Perhaps you can reproduce the issue in my fiddle? – James Montagne Feb 03 '12 at 22:00
  • Hang on, just looked at your edit, your code won't do anything. `$(this).find(...` will return nothing as `this` is an input which does not **contain** anything. Is your html actually different than what you posted? – James Montagne Feb 03 '12 at 22:02
  • woops, that was a typo.. i meant to seek from the top level's parent `li` – tester Feb 03 '12 at 22:06
  • you know, it must be a method that gets called later in the chain that is toggling the checked attribute. thanks for helping. the problem must be elsewhere. – tester Feb 03 '12 at 22:09
  • "The change event occurs when a control loses the input focus and its value has been modified since gaining focus." No focus change means no change event. http://www.w3.org/TR/DOM-Level-2-Events/events.html#Events-eventgroupings-htmlevents – Cheekysoft Oct 31 '14 at 11:18
1

try to unbind the onchange listener, then bind it again once the property has been set.

Drew Dahlman
  • 4,952
  • 1
  • 22
  • 34
1

Right now your selector targets all input elements. You can give your main checkbox an Id, and the others a common class.

<li>
<input id="main-chk"type="checkbox" />
   <ul>
   <li>
     <input class="children" type="checkbox" />

    $('li:first').bind('change', function() {
       $(this).find('li').prop('checked', 'checked');
    }); // exists elsewhere, cannot change
Jack
  • 8,851
  • 3
  • 21
  • 26