Angelo Badellino
Angelo Badellino

Reputation: 2199

Knockout and checked data-bind

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?

Upvotes: 1

Views: 568

Answers (2)

Fabian Schmengler
Fabian Schmengler

Reputation: 24576

SelectedYears is a ko.observableArray which is not an array by itself even if it exposes some methods of Array. But there is no length property. To get the actual array and retrieve the size, use:

alert(this.SelectedYears().length);

However, the rest of your code might not work as you intended, because you cannot use the checked binding with an array like that:

data.bind="checked: $root.SelectedYears"

checked needs something that evaluates to true or false, you might consider a writable computed observable to bind the checkboxes to your SelectedYears array.

Upvotes: 2

Paul Manzotti
Paul Manzotti

Reputation: 5147

Try:

alert(this.SelectedYears().length);

It's an observable, so you need to call it as one.

Upvotes: 1

Related Questions