简体   繁体   中英

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?

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.

Try:

alert(this.SelectedYears().length);

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM