简体   繁体   中英

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

  • 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> 
  • Delete Witness
  • Add Witness

TODO

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

  • If it is toggled by the user to 'No'(unchecked) we make the witness display area INVISIBLE (ideally, remove from DOM) and delete all of the Witness objects.
  • If it is toggled to 'Yes'(checked) we make the witness display area VISIBLE and make sure there is at least one 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

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" />

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM