I have several checkboxes, or, should I say, several bootstrap toggles:
<input id="master-toggle" type="checkbox" data-toggle="toggle">
<input type="checkbox" class="slave-toggle" data-toggle="toggle">
<input type="checkbox" class="slave-toggle" data-toggle="toggle">
What I'm trying to do is toggle every slave-toggle
when the master-toggle
is toggled. To do that, I wrote the following code:
$('#master-toggle').change(() => {
if($(this).prop('checked')) {
$('.slave-toggle').each(() => {
$(this).prop('checked', true).change();
});
} else {
$('.slave-toggle').each(() => {
$(this).prop('checked', false).change();
});
}
});
So, when the master-toggle
is toggled, the function executes, checking the value of the "checked" property. If the "checkbox" is "checked", then it iterates over all elements of the slave-toggle
class, and sets their "checked" property to true. Same thing for when master-toggle
is "unchecked". Right?
Well the thing is, I've run into 2 issues. First, the $(this).prop('checked')
expression in the if
statement always evaluates to undefined
. Second, even if I force this value, executing the $(this).prop('checked', true).change()
inside the each
function doesn't change either slave-toggle
's status. What gives? What am I doing wrong?
Any help is greatly appreciated. Here's the jsfiddle link.