javascript - Knockout js checkbox checked binding - Stack Overflow

admin2025-04-03  0

In knockout js am trying to perform a foreach on an array of data to display check boxes. The issue I am having is that the checked databind does not appear to run until I interact with one of the boxes. For example, below I am generating 5 text boxes none of which are showing up as checked. However when I click "one", "two" and "four" also get checked as they should have been from the beginning.

Javascript:

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);

HTML:

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

Fiddle is at: /

Thanks for your help.

In knockout js am trying to perform a foreach on an array of data to display check boxes. The issue I am having is that the checked databind does not appear to run until I interact with one of the boxes. For example, below I am generating 5 text boxes none of which are showing up as checked. However when I click "one", "two" and "four" also get checked as they should have been from the beginning.

Javascript:

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);

HTML:

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

Fiddle is at: http://jsfiddle/bvGG3/1/

Thanks for your help.

Share Improve this question asked Aug 5, 2013 at 15:46 gth685fgth685f 5852 gold badges6 silver badges13 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 12

In Knockout before version 3.0 the bindings fired in order, so your problem is that your checked binding fires before your attr binding.

So you need to change the order of your bindings:

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

Demo JSFiddle.

Or your original code will work when you update to 3.0 (demo JSFiddle).

转载请注明原文地址:http://conceptsofalgorithm.com/Algorithm/1743632463a213954.html

最新回复(0)