Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 310
Marcel Gruber Avatar asked Jan 20 '26 16:01

Marcel Gruber


1 Answers

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

like image 88
haim770 Avatar answered Jan 23 '26 05:01

haim770



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!