KnockoutJS + Advanced Checkbox Function
This checkbox is advanced in that not only is it checked based on existing data, but the page also needs to react in several ways when the user changes the checkbox by manually checking or unchecking the checkbox.
Imagine you have murderCaseModel
a list of different Witnesses
crimes for.
Here's a script for you:
http://jsfiddle.net/maxgrr/j6fm7162/6/
The requirements are as follows:
Already done
-
If the previous ones
Witnesses
exist from the loaded data, set the statuschecked
for the page load window<input type='checkbox' data-bind='checked: numWitnesses() > 0'></input>
- Delete
Witness
- Add to
Witness
TODO
Enabling a checkbox causes another region to appear or disappear on the page
- If the user switches to None (not checked), we create an INVISIBLE witness display area (ideally, remove from the DOM) and remove all objects
Witness
. - If it is toggled to Yes (checked), we create a VISIBLE witness viewport and make sure that the user has at least one object
Witness
to be populated by the user.
This whole problem is very complicated for me and defines the auto value for the checkbox, but also the user-selected value for which it is difficult to understand. Any help is much appreciated. This is awesome functionality!
source to share
You can use computed
to make the field a wereThereAnyWitnesses
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
source to share
You can use jQuery. First, make sure you include the jQuery libraries in your header tags. Just copy the following code into your headers:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
Then, use the following code to check if the checkbox is checked:
<script type="text/javascript">
if ($('#the_checkbox').is(":checked"))
{
$('#the_textarea').hide();
}
</script>
And here is the input:
<input type="checkbox" id="the_checkbox" />
source to share