This checkbox is advanced in that not only is it set based on existing data, but the page must also respond in several ways to the user changing the checkbox by manually checking or unchecking it.
Imagine you have a murderCaseModel with list of various Witnesses to a crime.
Here is a Fiddle for you:
http://jsfiddle.net/maxgrr/j6fm7162/6/
The requirements are as follows:
Already Done
If previous witnesses exist from the loaded data, set the checked status of the box on page load
<input type='checkbox' data-bind='checked: numWitnesses() > 0'></input>
WitnessWitnessTODO
Toggling the checkbox causes another area on the page to appear or disappear
Witness objects.Witness object ready to be filled out by the user.This whole problem is very tricky to me and determining the auto value for the checkbox but also the user selected value for it it difficult to grasp. Any help is much appreciated. It's a cool functionality!
You can use a computed to make your wereThereAnyWitnesses field a little smarter:
self.wereThereAnyWitnesses = ko.computed({
read: function() {
return self.numWitnesses() > 0;
},
write: function(wereThereAnyWitnesses) {
if (!wereThereAnyWitnesses && self.numWitnesses() > 0) {
if (!confirm("Remove all current witnesses?"))
return self.wereThereAnyWitnesses.notifySubscribers();
else
self.witnesses.removeAll();
}
if (wereThereAnyWitnesses && self.numWitnesses() == 0)
self.addWitness();
}
}, this);
And in your HTML:
<input type='checkbox' data-bind='checked: wereThereAnyWitnesses' />
See Fiddle
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With