I am triyng to get the selected checkbox in this scenario:
<div id='main'>
<table>
<tbody data-bind="foreach: Years">
<tr>
<td>
<input type="checkbox" data.bind="checked: $root.SelectedYears"/>
</td>
<td><span data-bind="text: descr" />
</td>
</tr>
</tbody>
</table>
<br>
<input type="button" value="Click!" data-bind="click: count">
<div/>
function vm() {
this.Years =
[
{
code: "2011",
descr: "descr 2011"
},
{
code: "2012",
descr: "descr 2012"
},
{
code: "2013",
descr: "descr 2013"
},
{
code: "2014",
descr: "descr 2014"
}
];
this.SelectedYears = ko.observableArray(this.Years);
count = function()
{
alert(this.SelectedYears.length);
};
return this;
}
ko.applyBindings(new vm());
http://jsfiddle.net/angelobadellino/UXKt9/
Whene I click on the button, my SelectedYears collection is empty. It should be filled with the selected checkboxes instead.
can you help me to understand where I am wrong?
SelectedYearsis ako.observableArraywhich is not an array by itself even if it exposes some methods ofArray. But there is nolengthproperty. To get the actual array and retrieve the size, use:However, the rest of your code might not work as you intended, because you cannot use the
checkedbinding with an array like that:checked needs something that evaluates to true or false, you might consider a writable computed observable to bind the checkboxes to your
SelectedYearsarray.