Working with checkboxes in knockoutjs

http://stackoverflow.com/questions/6736136/working-with-checkboxes-in-knockoutjs

by kougiland

HTML

<script src="http://rniemeyer.github.com/KnockMeOut/Scripts/jquery.tmpl.js"></script>
<script src="http://knockoutjs.com/downloads/knockout-1.2.1.debug.js"></script>
<ul data-bind="template: { name: 'choiceTmpl', foreach: choices, templateOptions: { selections: selectedChoices } }"></ul>

<script id="choiceTmpl" type="text/html">
    <li>
        <input type="checkbox" data-bind="attr: { value: $data }, checked: $item.selections" />
        <span data-bind="text: $data"></span>
    </li>
</script>

<hr />

<div data-bind="text: ko.toJSON(selectedChoices)"></div>

<hr />

<div data-bind="text: selectedChoicesDelimited"></div>

JavaScript

var viewModel = {
    choices: ["one", "two", "three", "four", "five"],
    selectedChoices: ko.observableArray(["two", "four"])
};

viewModel.selectedChoicesDelimited = ko.dependentObservable(function() {
    return this.selectedChoices().join(",");
}, viewModel);

ko.applyBindings(viewModel);