Knockout Checkbox List Selected Binding
Using Knockout to bind a list of Checkbox List to a Selected Object Array Example
by sas_sam
HTML
<script src="http://github.com/downloads/SteveSanderson/knockout/knockout-2.0.0.js"></script>
<div id="base">
<ul data-bind="foreach: people">
<li>
<input type="checkbox" data-bind="click: $parent.addPerson, value: id, checked: $parent.checkedPeople, attr: {id: 'checkBox' + id}">
<label data-bind="text: name, attr:{for: 'checkBox'+id}"></label>
</li>
</ul>
<div data-bind="text: ko.toJSON($root)"></div>
</div>
JavaScript
function Person(id,name,age) {
this.id = id;
this.name = name;
this.age = age;
}
var listOfPeople = [
new Person(1, 'Fred', 25),
new Person(2, 'Joe', 60),
new Person(3, 'Sally', 43)
];
var viewModel = {
people: ko.observableArray(listOfPeople),
selectedPeople: ko.observableArray(),
checkedPeople: ko.observableArray(),
addPerson: function(person, elem) {
var $checkBox = $(elem.srcElement);
var isChecked = $checkBox.is(':checked');
//If it is checked and not in the array, add it
if(isChecked && viewModel.selectedPeople.indexOf(person) < 0) {
viewModel.selectedPeople.push(person);
}
//If it is in the array and not checked remove it
else if(!isChecked && viewModel.selectedPeople.indexOf(person) >= 0) {
viewModel.selectedPeople.remove(person);
}
//Need to return to to allow the Checkbox to process checked/unchecked
return true;
}
};
ko.applyBindings(viewModel, $("#base")[0]);