سؤال

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?

هل كانت مفيدة؟

المحلول

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

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top