Enable/Disable button using checkboxes

1k Views Asked by At

I need to enable/disable button if both checkboxes are checked. I want to do in knockout.js. I am still a beginner. I have found an example enable/disable button using checkbox but that is doing for 1 checkbox. In my scenario, i have two checkboxes and they both should be checked to enable the button. If any of the checkbox is not checked then the button should be disabled.

<input type="checkbox" data-bind="checked: myBoolean" />
<button data-bind="enable: myBoolean">My Button</button>

ko.applyBindings({ myBoolean: ko.observable(true) });

Any help or suggestion would be appreciated.

Thanks in advance

2

There are 2 best solutions below

2
Philip Bijker On BEST ANSWER

You could

  1. add another observable for the other checkbox
  2. add a computed observable for the button, which returns true only when both checkboxes are checked (observables are true)

var test = { 
  myBoolean1: ko.observable(false),
  myBoolean2: ko.observable(false)
};
test.myComputed = ko.computed(function() { return test.myBoolean1() && test.myBoolean2() });

ko.applyBindings(test);
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script>
<input type="checkbox" data-bind="checked: myBoolean1" />
<input type="checkbox" data-bind="checked: myBoolean2" />
<button data-bind="enable: myComputed">My Button</button>

1
Gerard On

You can do this using CSS only. Unless you need to support IE10 or lower.

button {
  cursor: not-allowed;
  pointer-events: none;
  color: grey;
  background-color: white;
}

#firstCheckbox:checked+#secondCheckbox:checked+button {
  color: black;
  cursor: pointer;
  pointer-events: auto;
}
<input type="checkbox" id="firstCheckbox">
<input type="checkbox" id="secondCheckbox">
<button>Click me</button>