I have list of objects I can select. I made a select all checkbox to click which selects all. The selecting works, but it doesn't update the checkbox value itself. Also, deselecting doesn't work, because the value is never true.
//html
<input type="checkbox" data-bind="checked: selecAllBT, click: selectAll" /> Select all
//other stuff
//JS
self.selecAllBT = ko.observable(false);
self.selectAllBodyTypes = function (self) {
for (i = 0; i < self.items().length; i++) {
if (self.selecAllBT() != self.items()[i].selected()){
self.toggleSelected(self.items()[i]);
}
}
self.selecAllBT(!self.selecAllBT);
return true;
}
I put it in a JSFiddle: https://jsfiddle.net/5mquej1f/21/ (I actually reused a JSFiddle from another issue of me, in case somebody recognizes it: knockout observablearray in 2 templates)
Anyone an idea what I'm doing wrong? thx
You're implementing the same functionality twice:
The checkbox has toggle behaviour by default, implemented by your browser. Knockout plugs in to this functionality using the
checkedbinding. You pass it an observable, and the value is stored:The problem
Now, you've also included a
clickbinding. This binding listens to aclickon any element. In your click listener, you toggle the value by:Then, you
return true, passing the event to the checkbox. The checkbox will change naturally, and bound value will toggle again, changing it back to the old value.Solution
A better way of implementing this, is removing the
clicklistener and adding asubscribeto your checkbox value in the code behind: