Marcel Gruber
Marcel Gruber

Reputation: 7525

KnockoutJS + Advanced Checkbox Functionality

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

TODO

Toggling the checkbox causes another area on the page to appear or disappear

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!

Upvotes: 3

Views: 57

Answers (2)

haim770
haim770

Reputation: 49123

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

Upvotes: 3

Arshia
Arshia

Reputation: 117

You can use jQuery. First, make sure you have included jQuery libraries in you head tags. Just copy the following code in your head tags:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>

Then, use the following code to see if the check box 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" />

Upvotes: 1

Related Questions