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?