0
votes

I've got a scenario in which I've got multiple checkboxes, and for each checkbox, all other checkboxs' values should change (and their corresponding observables should be updated) to false whenever any other checkbox is selected. Basically, the checkboxes should behave like radio buttons, but each is tied to a database field.

<input type="checkbox" data-bind="checked: NameIsJohn">John</input>
<input type="checkbox" data-bind="checked: NameIsJerry">Jerry</input>
<input type="checkbox" data-bind="checked: NameIsJenny">Jenny</input>
<input type="checkbox" data-bind="checked: NameIsJake">Jake</input>
<input type="checkbox" data-bind="checked: NameIsJeffrey">Jeffrey</input>
<input type="checkbox" data-bind="checked: NameIsJack">Jack</input>

var vm = function() {
    this.NameIsJohn = ko.observable();
    this.NameIsJerry = ko.observable(true);
    this.NameIsJenny = ko.observable();
    this.NameIsJake = ko.observable();
    this.NameIsJeffrey = ko.observable();
    this.NameIsJack = ko.observable();   
};

One approach would be to use jQuery to attach a click handler to every checkbox, but this doesn't seem update the underlying observables.

//var variable = the input element
$variable.filter(':checked').not(this).removeAttr('checked');

Another approach would be to use a custom Knockout function, or some sort of custom subscription. What I came up with works, but it's hacky. Imagine if there were ten or more observables to update!

vm.ChangeCheckbox = function (CheckboxName) {
                vm.NameIsJohn(false);
                vm.NameIsJerry(false);
                vm.NameIsJenny(false);
                vm.NameIsJake(false);
                vm.NameIsJohn(false);
                vm.NameIsJohn(false);
                if (CheckboxName === 'John') {
                    vm.NameIsJohn(true);
                }   else if (CheckboxName === 'Jerry') {
                    vm.NameIsJerry(true);
                } ...
//etc.

Is there a more dynamic way of updating all of the observables in this set when a checkbox is clicked?

1
@mhu It looks like this solution requires the manual construction of a pretty big observable array - so I'm not sure if the approach offers me any advantage over the ChangeCheckbox() function that I've got in my question. Both approaches seem wordy; not really dynamic - alex
This can be a start jsfiddle.net/supercool/f8o3ua9k/1 . it's already 2am here gotta go . cheers - super cool

1 Answers

1
votes

It seems sensible to me to have one variable that indicates which is the checked box -- you would set it upon a click -- and all the buttons' checked properties are attached to computed observables whose function is basically "am I the one?"

this.NameIsJohn = ko.computed(isIt('John'));