MDE E
MDE E

Reputation: 7

Complementary State with 2 checkboxes in knockout.js

I have two checkboxes That I would like to have complementary states.

for example: one checkbox is initially selected, so automatically, the other one is unchecked. If I toggle each one of them, the other one toggles too, but with a complementary state.

How can I do this with html and ko.js?

Upvotes: 0

Views: 85

Answers (2)

Ray
Ray

Reputation: 3959

Edit: After seeing your comments, hope I've got this right.

  1. You want the initial values to come from another viewmodel.
  2. Both checkboxes can be unchecked but only 1 can be checked at a time after the initial setting is done. Correct? In this case writable computed observables are no longer required.

var viewmodel1 = function(){
  var self = this;
  self.initialValueCheckA = false;
  self.initialValueCheckB = true;
};

var viewmodel2 = function(data){
  var self = this;
  self.checkA = ko.observable(data.initialValueCheckA);
  self.checkB = ko.observable(data.initialValueCheckB);
  
  self.checkA.subscribe(function(newAValue){
    if(newAValue){
      self.checkB(false);
    }
  });
  
  self.checkB.subscribe(function(newBValue){
    if(newBValue){
      self.checkA(false);
    }
  });
  
};

var instance1 = new viewmodel1();
var instance2 = new viewmodel2({
  initialValueCheckA: instance1.initialValueCheckA,
  initialValueCheckB: instance1.initialValueCheckB
});
ko.applyBindings(instance1, document.getElementById('section1'));
ko.applyBindings(instance2, document.getElementById('section2'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script>

<div id="section1">
  A
  <input type="checkbox" data-bind="checked: initialValueCheckA" />
  B
  <input type="checkbox" data-bind="checked: initialValueCheckB" />
</div>

<div id="section2">
  A
  <input type="checkbox" data-bind="checked: checkA" />
  B
  <input type="checkbox" data-bind="checked: checkB" />
</div>

Upvotes: 0

Jonathan Gagne
Jonathan Gagne

Reputation: 4389

No need any library to do it. You can use it with pure JavaScript as below.

var cb = document.querySelectorAll('input[type=checkbox]');

let toggleCb = function(i){
  let index = i ? 0 : 1;
  cb[index].checked = !cb[index].checked;
}

for(let i=0; i<=1; i++){
  cb[i].onclick = function(){
    toggleCb(i);
  }
}
<input type="checkbox" id="cb1" checked />
<input type="checkbox" id="cb2" />

Upvotes: 1

Related Questions