根据可观察数​​组的内容选中一个复选框

时间:2015-08-30 07:22:07

标签: knockout.js

我对使用knockout js的复选框绑定感到震惊。我使用两个可观察的数组。第一个可观察数组用于显示所有学生详细信息值,并在视图中显示复选框。在第二个可观察数组中,我获取了一些需要在视图中动态检查(true)的值,我已经使用整个值显示了复选框。我的HTML代码是,

<div class="col-lg-10" style="white-space:pre">
    <div class="checkbox-inline" data-bind="foreach: $root.Studentdetails">
        <input type="checkbox" data-bind="
            checkedValue: $data,value:id(),
            checked: $root.associatedItemIds,
            click: $root.toggleAssociation
        " />
        <span data-bind="text: '&nbsp;' + Name()"></span>
    </div>
</div>

这是我获取复选框selecetd的方法,

self.associatedItemIds=ko.obsearvablearray();   
self.associatedItemIds.push(response.CheckStudents);

2 个答案:

答案 0 :(得分:3)

您可以通过对象引用来检查复选框(即使用$data)。然后,您将拥有一系列选定的学生

或者您通过值(例如学生ID)检查复选框。然后你将有一个学生ID 的数组。

在任何情况下,您都不需要任何click处理程序或value绑定,因此knockout会自行完成所有操作。花一些时间再次阅读the documentation

比较

&#13;
&#13;
function StudentList(students) {
  this.Studentdetails = ko.observableArray(students);
  this.associatedItems = ko.observableArray();
}

var students = [
  {Id: 1, Name: 'Student 1'},
  {Id: 2, Name: 'Student 2'},
  {Id: 3, Name: 'Student 3'},
  {Id: 4, Name: 'Student 4'}
];

var vm = new StudentList(students);
vm.associatedItems.push(students[2]);
ko.applyBindings(vm);
&#13;
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.2.0/knockout-min.js"></script>

<div class="col-lg-10">
    <div class="checkbox-inline" data-bind="foreach: $root.Studentdetails">
        <input type="checkbox" data-bind="
            checkedValue: $data,
            checked: $root.associatedItems,
        " />
        <span data-bind="text: Name"></span><br>
    </div>
</div>

<pre data-bind="text: ko.toJSON($root, null, 2)"></pre>
&#13;
&#13;
&#13;

&#13;
&#13;
function StudentList(students) {
  this.Studentdetails = ko.observableArray(students);
  this.associatedItemIds = ko.observableArray();
}

var students = [
  {Id: 1, Name: 'Student 1'},
  {Id: 2, Name: 'Student 2'},
  {Id: 3, Name: 'Student 3'},
  {Id: 4, Name: 'Student 4'}
];

var vm = new StudentList(students);
vm.associatedItemIds.push(students[2].Id);
ko.applyBindings(vm);
&#13;
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.2.0/knockout-min.js"></script>

<div class="col-lg-10">
    <div class="checkbox-inline" data-bind="foreach: $root.Studentdetails">
        <input type="checkbox" data-bind="
            checkedValue: Id,
            checked: $root.associatedItemIds,
        " />
        <span data-bind="text: Name"></span><br>
    </div>
</div>

<pre data-bind="text: ko.toJSON($root, null, 2)"></pre>
&#13;
&#13;
&#13;

答案 1 :(得分:0)

 <input type="checkbox" data-bind="attr: { id: 'chl'+Id},value: Id, checked:$root.associatedItemIds">

  self.associatedItemIds = ko.observableArray();

  for (var key in self.ProductsList()) {
            self.associatedItemIds.push("" + self.ProductsList()[key].Id);
        }