Skip to content Skip to sidebar Skip to footer

Checkbox Property Check Value Not Updating In Knockout Js

I am working with Knockout.js. I have a page where I have three checkbox and its under foreach loop. Here is my code:
&

Solution 1:

You can use subscribe feature to identify if a checkbox is checked then modify the other checkbox. And also I prefer to arrange the viewmodel this way.

var singleViewModel = function(element){
  varself = this;
  // self.otherSafetyPro = ko.observableArray([]);self.VId = ko.observable(element.VId);
  ...
  self.Completed = ko.observable(element.AlreadyCompleted);
  self.NotApplicable = ko.observable(element.NotApplicable);
  self.CreateNew = ko.observable(element.CreateNew);
  self.Completed.subscribe(function(newValue) {
    if(newValue) {
      self.NotApplicable(false);
      self.CreateNew(false);
    }
  });
  self.NotApplicable.subscribe(function(newValue) {
    if(newValue) {
      self.Completed(false);
      self.CreateNew(false);
    }
  });
  self.CreateNew.subscribe(function(newValue) {
    if(newValue) {
      self.NotApplicable(false);
      self.Completed(false);
    }
  });
}

And then this is how you assign it

$(data.TemplateProcedure).each(function (index, element) {
  viewModel.procedures.push(newsingleViewModel(element));
});

Another sample:

functionViewModel() {
  var self = this;
  self.optionA = ko.observable(false);
  self.optionA.subscribe(function(newValue){
    if(newValue) {
      self.optionB(false);
      self.optionC(false); 
    }
  });
  self.optionB = ko.observable(false);
  self.optionB.subscribe(function(newValue){
    if(newValue) {
      self.optionA(false);
      self.optionC(false); 
    }
  });
  self.optionC = ko.observable(false);
  self.optionC.subscribe(function(newValue){
    if(newValue) {
      self.optionA(false);
      self.optionB(false); 
    }
  });
}   

$(document).ready(function () {
  var myViewModel = newViewModel();
  ko.applyBindings(myViewModel);
});
<scriptsrc="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><scriptsrc="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.2.0/knockout-min.js"></script><div><inputtype="checkbox"data-bind="checked: optionA" /><inputtype="checkbox"data-bind="checked: optionB" /><inputtype="checkbox"data-bind="checked: optionC" /></div>

Post a Comment for "Checkbox Property Check Value Not Updating In Knockout Js"