Knockout checkboxes with array?
knockout.js
Solution
I think all you should have to do is use a `checked` data-binding with the observable array. Knockout will update the observable array automatically when you check an item.
Also note that I added a `value` binding that binds the `value` of each checkbox to the `documentId`.
View:
<!-- ko foreach: documents -->
<div>
<input type="checkbox" data-bind="checked: $parent.selectedDocuments, value: documentId" />
</div>
<!-- /ko -->
<!-- ko foreach: selectedDocuments -->
<div>
<span data-bind="text: $data"></span>
</div>
<!-- /ko -->
ViewModel:
var selectedDocuments = ko.observableArray();
var viewModel = {
documents: [{"documentId": "1"}, {"documentId": "2"}, {"documentId": "3"}],
selectedDocuments: selectedDocuments
};
ko.applyBindings(viewModel);
Example: http://jsfiddle.net/PTSkR/37/
As a side note, I would avoid attaching properties to `window` if at all possible. You could use a lightweight namespacing pattern or use a simple pub/sub system with KnockoutJS.
Problem
I know this topic has been addressed a few times but I'm having a bit of trouble here. I have the following in my view: ``` <!-- ko foreach: documents --> <div> <input type="checkbox" data-bind="checked: $parent.checkItem(documentId)" /> </div> <!-- /ko --> ``` In my viewModel: ``` var checkItem = function (checkedItem) { debugger; window.selectedDocuments.push(checkedItem); }; ``` I'm using window because another resource needs access to this array. Right now, when I load the page the checkItem is hit one time for each document, which I don't think it should. I'm trying to monitor which documents have been selected, keeping an array updated (in this case, selectedDocuments). Here's a fiddle with my attempt: http://jsfiddle.net/PTSkR/36/ How can I make this work?