简体   繁体   中英

Knockout js checkbox is not checked when setting selected values in the view model

My problem is when I set the values of the selected checkboxes through the viewmodel the checkboxes aren't checked until I click another checkbox.

HTML:

<input type="checkbox" data-bind="checked: selectedTags, attr: {value: '1', id: '1'}" /> 1
<input type="checkbox" data-bind="checked: selectedTags, attr: {value: '2', id: '2'}" /> 2
<input type="checkbox" data-bind="checked: selectedTags, attr: {value: '3', id: '3'}" /> 3

<button data-bind="click: alertMe">Click Me</button>

JAVASCRIPT:

function ViewModel () {
    var self = this;
    
    self.selectedTags = ko.observableArray([]);

    // I added 1 to the selected tags array
    self.selectedTags().push('1');
    
    self.alertMe = function () {
        alert(self.selectedTags());
    };
}

The correct way of adding items to an observableArray is to call push directly on the observableArray (this way KO will be notified that your array was changed):

self.selectedTags.push('1'); //no () after selectedTags

In itself it won't solve your problem because you are setting the value of the checkboxes with the attr binding, and Knockout (before version 3.0) fires the bindings in order. So your checked binding gets executed first which does not find the values so it cannot set your checkboxes.

You can upgrade to knockout 3.0 to solve this or change the order of your bindings:

<input type="checkbox" 
       data-bind="attr: {value: '1', id: '1'}, checked: selectedTags" /> 1
<input type="checkbox" 
       data-bind="attr: {value: '2', id: '2'}, checked: selectedTags" /> 2
<input type="checkbox" 
       data-bind="attr: {value: '3', id: '3'}, checked: selectedTags" /> 3

Demo JSFiddle .

Just edit HTML:

<input type="checkbox" data-bind="checked: selectedTags" value="1" id="1" /> 1
<input type="checkbox" data-bind="checked: selectedTags" value="2" id="2" /> 2
<input type="checkbox" data-bind="checked: selectedTags" value="3" id="3" /> 3

<button data-bind="click: alertMe">Click Me</button>

http://jsfiddle.net/eHj5X/6/

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