Search code examples
knockout.jsknockout-2.0knockout-mapping-pluginknockout-validationknockout-mvc

Disabling checkbox using KnockoutJS


I am unable to disable the checkbox when the length of observable array reaches a specific limit. Here is the link to code : http://jsfiddle.net/pLNdc/59/

<ul class="options" data-bind="foreach: choices">
<li><label><input type="checkbox" name="NotifyMembers"
    data-bind="attr: { value: $data },
               checked: $parent.selectedChoices,
               enable: $parent.selectedChoices.length < 2" />
    <span data-bind="text: $data"></span></label></li>
</ul>
<hr />

var viewModel = {};

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

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

ko.applyBindings(viewModel);

Thanks.


Solution

  • Since selectedChoices is an observable, you need to call it with parens before accessing its length property, like this:

    <input type="checkbox" name="NotifyMembers"
           data-bind="attr: { value: $data },
                      checked: $parent.selectedChoices,
                      enable: $parent.selectedChoices().length < 2" />