javascriptknockout.jsknockout-validationknockout-3.0knockout-mvc

Enable/Disable button using checkboxes


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


Solution

  • 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>