cosh
cosh

Reputation: 480

Toggling several checkboxes on separate toggle change

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.

Upvotes: 0

Views: 32

Answers (1)

Taplar
Taplar

Reputation: 24965

The issues you are running into are in regards to your use of arrow functions.

() => {}

Arrow functions do not change what this is within their context. It is one of their features. In order to reference this as you are expecting, use normal functions. Otherwise, the e.target on the change event should be the element changed, and the each method should pass in the arguments index, element that you can reference.

Upvotes: 2

Related Questions