0

I've got a bunch of checkboxes that I want to have trigger a callback when their state is toggled, so I added this (working) line:

$('.main').change(mainChecked);

And then in the mainChecked method I look at the this variable and do the appropriate thing whether it was checked or not. Now, elsewhere in my code I want to check some of those so I just did:

$('[data-auto-select]').attr('checked', 'checked');

My problem is that while they do get checked, the mainChecked() function doesn't get called for them. How do I check them in such a way that the mainChecked() method also automatically gets called?

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Gargoyle
  • 9,590
  • 16
  • 80
  • 145
  • 1
    That's answered here :) http://stackoverflow.com/a/4870054/448865 Thanks Cp – cpreid Dec 05 '13 at 16:53
  • possible duplicate of [Why isn't my checkbox change event triggered?](http://stackoverflow.com/questions/4869981/why-isnt-my-checkbox-change-event-triggered) – Felix Kling Dec 05 '13 at 17:08

1 Answers1

2

when you use script to change the value of an input element the change event will not get triggered, though you can manually trigger it

$('[data-auto-select]').prop('checked', true).change();
//or $('[data-auto-select]').prop('checked', true).trigger('change');

Also use .prop() to set the checked state instead of .attr()

Arun P Johny
  • 384,651
  • 66
  • 527
  • 531