Knockout.js checkbox checked and click event
David Reid
We are trying to implement checkboxes and lists with the following functionality:
- Clicking the checkbox will clear the array (if there are items in it), or add a new item (if there are none).
- When the delete button is clicked, an item is removed from the array, once the last item is removed, the checkbox automatically unchecks itself.
The problem I'm having is that if you click to remove each array item, and then click the checkbox to add a blank entry, I want the checkbox to be checked again (based on which observable is checked), but it's not ?
I have the following code:
<div>
<input type="checkbox" data-bind="checked: PreviousSurnames().length > 0, click: $root.PreviousSurnames_Click" />Previous Surname(s)?
</div>
<div data-bind="foreach: PreviousSurnames">
<div>
<input type="text" data-bind="value: $data">
<span data-bind="click: $root.removePreviousSurname">Remove</span>
</div>
</div>
var myViewModelExample = function () {
var self = this;
self.PreviousSurnames = ko.observableArray(['SURNAME1', 'SURNAME2', 'SURNAME3']);
self.removePreviousSurname = function (surname) {
self.PreviousSurnames.remove(surname);
};
self.PreviousSurnames_Click = function () {
if (self.PreviousSurnames().length === 0) {
self.PreviousSurnames.push('');
}
else {
self.PreviousSurnames.removeAll();
}
alet(2)
}
}
ko.applyBindings(new myViewModelExample());
east david
You need to use a calculation to monitor the length of the observable array. This way you can automatically react to the length when it reaches zero.
self.surnames = ko.computed(function() {
var checked = true;
if (self.PreviousSurnames().length === 0) {
self.PreviousSurnames.push('');
checked = false;
}
return checked;
});
Now, after clearing all names, you will see a blank text box. If you update the binding on the checkbox, the binding will work fine as well.
<input type="checkbox" data-bind="checked: surnames, click: PreviousSurnames_Click" />Previous Surname(s)?