Checkbox selectAll/De-selectAll using knockout

Checkbox selectAll/De-selectAll using knockout

by Keyur Patel

HTML

<table>
    <thead>
        <tr>
            <th>Name</th>
            <th><input type="checkbox" data-bind="checked: SelectAll" /></th>
        </tr>
    </thead>
    <tbody data-bind="foreach: $data.People">
        <tr>
            <td data-bind="text: Name"></td>
            <td class="center"><input type="checkbox" data-bind="checked: Selected" /></td>
        </tr>
    </tbody>
</table>

JavaScript

function MasterViewModel() {
    var self = this;

    self.People = ko.observableArray([new Person("Test1"), new Person("Test2")]);
    self.SelectAll = ko.computed({
        read: function() {
            var item = ko.utils.arrayFirst(self.People(), function(item) {
                return !item.Selected();
            });
            return item == null;           
        },
        write: function(value) {
            ko.utils.arrayForEach(self.People(), function (person) {
                person.Selected(value);
            });
        }
    });
}


Person = function (name) {
    
    this.Name = name;
    this.Selected = ko.observable(false);
}

ko.applyBindings(new MasterViewModel());