简体   繁体   中英

checkbox array in knockout being all checked on click

I am having an issue with knockout, when i check a box, they're all being checked...

this is what I have: _Categories_List has all the items, and My_categories is the empty list where I want to have each id added

this is the code:

 <!-- ko foreach: _Categories_List --> 
    <input type="checkbox" data-bind="attr: {value: $data}, checked: $root.My_categories" />
    <span data-bind="text: CODE"></span><br />
 <!-- /ko -->

and this is the JS part of the code (i cant really change this as to how the code is in the documentation because i'm building off someone else's work and should use the same code - referring to the mapping.fromJS):

var Poi = new Object();  
Poi.My_categories = [];
var _Poi = ko.mapping.fromJS(Poi);

var Categories_List = [];
var _Categories_List = ko.mapping.fromJS(Categories_List);

$(document).ready
(
    function () {        
       ko.applyBindings(_Poi);
       // here there's an ajax function to load the categories returned in i_Input.My_Result, then:
       ko.mapping.fromJS(i_Input.My_Result, _Categories_List);
    }
);

this is what the object loaded from ajax looks like:

{"My_Result":[
  {"CODE":"chalet","DEF_POIS_CATEGORY_ID":2,"DESCRIPTION":"chalet","ENTRY_DATE":"2012-10-10","ENTRY_USER_ID":2,"OWNER_ID":1},
  {"CODE":"vila","DEF_POIS_CATEGORY_ID":3,"DESCRIPTION":"villa","ENTRY_DATE":"2012-10-10","ENTRY_USER_ID":2,"OWNER_ID":1}
]}

The checked binding works off of the value of the input element. In your code, you are setting the value equal to an object, which turns into [object Object] , so both of your inputs have the same value, which is why checking one toggles both.

So, you would want to set your value equal to a key on the object like your CODE property. If necessary, then you can use a computed observable to represent the actual objects.

Here is a sample: http://jsfiddle.net/rniemeyer/7n9gR/

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