John
John

Reputation: 41

how to bind knockout checked checkboxes for a list of objects?

I am new to Knockout and am trying to bind checked checkboxes to a Knockout array.

var userRoleList = 
  [ ("UserTypeId": 1, "UserTypeName": "Admin")
    ("UserTypeId": 2, "UserTypeName": "NonAdmin")
    ("UserTypeId": 3, "UserTypeName": "Inspector")
  ]

Below is the code to display user role list in dropdownlist and to bind selected user role to knockout observable array, which is working perfectly fine.

 <td>                                         
    <select data-bind='options: $root.userRoleList, optionsText: "UserTypeName", optionsValue: "UserTypeId", optionsCaption: "Select...", value: UserTypeId'></select>                                                                                         
 </td>

Now I want to display checkbox list instead of dropdownlist (replace dropdown with checkbox) and I'm doing with following way, but the value is not binding to knockout observable array.

 <td>                                         
   <div class="userRole userRoleEdit" data-bind="foreach: $root.userRoleList">                                                
     <label data-bind="text: UserTypeName" style="width:50%"></label>                                                                                                  
     <input type="checkbox" data-bind=" attr: { value: UserTypeId, text:UserTypeName, id: UserTypeId, name: UserTypeName } " />                                                                                                
   </div>
 </td>

can you tell me what i am doing wrong?

Upvotes: 0

Views: 1450

Answers (1)

Ivan.Srb
Ivan.Srb

Reputation: 1851

Firstly, you are using incorrect array initialization syntax when creating userRoleList array. You should rewrite it like in the code below.

var viewModel = function () {
    var self = this;
    self.selectedRoleList = ko.observableArray([]);
    self.userRoleList = [{
        UserTypeId: 1,
        UserTypeName: "Admin"
    }, {
        UserTypeId: 2,
        UserTypeName: "NonAdmin"
    }, {
        UserTypeId: 3,
        UserTypeName: "Inspector"
    }];
}
var vm = new viewModel();
ko.applyBindings(vm);

Then, you should change your html:

<div data-bind="foreach: $root.userRoleList">
    <label data-bind="text: UserTypeName"></label>
    <input type="checkbox" data-bind="checked: $root.selectedRoleList, value: UserTypeId" />
</div>

And test it, if you want:

<div data-bind="foreach: $root.selectedRoleList">
    <label data-bind="text: $data"></label>
</div>

Upvotes: 1

Related Questions