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