简体   繁体   中英

Checkbox Logic in knockout.js

I have two checkboxes that I would like to implement following logic:

if both are OFF, that is allowed, if one checkbox is ON, if the other is to be ON (checked) then the first one must toggle to OFF and vice versa

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

This is the code that i got for toggling:

var viewmodel = function(){
  var self = this;
  self.checkA = ko.observable(true);
  self.checkB = ko.pureComputed({
    read: function(){
      return !self.checkA()
    },
    write: function(value){
      value? self.checkA(false) : self.checkA(true);
    },
    owner: self
  });
};

ko.applyBindings(new viewmodel());

<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script>

A
<input type="checkbox" data-bind="checked: checkA" />

B
<input type="checkbox" data-bind="checked: checkB" />

Since the value of B isn't merely a function of the value of A (both can be false) you'll have to have a second observable to store its state independently. Then for your logic I recommend using ko.subscribe instead of a computed function to react to the changes to either value.

 var viewmodel = function() { var self = this; self.checkA = ko.observable(true); self.checkB = ko.observable(false); self.checkA.subscribe(function(value) { if (value) self.checkB(false); //also clear B }); self.checkB.subscribe(function(value) { if (value) self.checkA(false); //also clear A }); }; ko.applyBindings(new viewmodel()); 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script> A <input type="checkbox" data-bind="checked: checkA" /> B <input type="checkbox" data-bind="checked: checkB" /> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM