Owais Ahmed
Owais Ahmed

Reputation: 1438

Multiple checkboxes state checked

I am using knockout Js. There are two checkboxes. If any checkbox is not checked then the submit button will be disabled. There might be cases where there will be 1 checkbox instead of 2 checkboxes. So I have a condition like this

 if ((self.checkBox1() === true && self.checkBox2() === true) || ($("#checkbox2").length <= 0 && self.checkBox1() === true) || ($("#checkbox1").length <= 0 && self.checkBox2() === true)) {
        $('.submit-btn').attr('disabled', false);

    } else {
        $('.submit-btn').attr('disabled', true);

    }
    return true;
}

This is a Jsfiddle sample I have created.

Is there a better way of doing this?

Upvotes: 0

Views: 334

Answers (2)

Nathan Fisher
Nathan Fisher

Reputation: 7941

Something like this would be a good start.

var ViewModel = function() {
  var self = this;
  self.checkBox1 = ko.observable(false);
  self.checkBox2 = ko.observable(false);
  self.submitEnabled = ko.pureComputed(function(){
    return self.checkBox1() && self.checkBox2();
  });
  self.submitForm = function(){
    alert("Woohoo, I can submit!!");
  }
};

ko.applyBindings(new ViewModel());
h3 {
  font-size: 120%;
  font-weight: bold;
  margin-top: 5px;
}

#bookform {
  margin: 10px;
  padding: 20px 20px 25px 20px;
  background-color: #eee;
}

input {
  width: 100%;
  padding: 4px;
}

.button {
  margin: 12px 0 0 0;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script>
<div id="bookform">
  <input type="checkbox" id="checkbox1" data-bind="checked: checkBox1"> Checkbox 1
  <input type="checkbox" id="checkbox2" data-bind="checked: checkBox2">Checkbox 2
  <button type="button" id="myBtn" class="btn btn-primary submit-btn" data-bind="click: submitForm, enable: submitEnabled">Submit</button>
</div>

Upvotes: 0

NerdyDeeds
NerdyDeeds

Reputation: 469

$('.submit-btn').attr('disabled', ![...document.querySelectorAll('[type="checkbox"]')].every(cb=cb.checked)));

In this case, we're checking that all checkboxes on the page are checked, a process that returns a true/false, and using that value to directly alter the disabled state on the button.

If the possibility exists that there are NON-required checkboxes on the same page too, a minor alteration to the querySelectorAll('[type="checkbox"]') portion would handle it: give the required CB's a class="required" (querySelectorAll('.required[type="checkbox"]'), or target their parent container (querySelectorAll('#parent [type="checkbox"]'

Upvotes: 0

Related Questions