knockout将checkboxlist选中的项目绑定到另一个checkboxlist

时间:2015-06-17 05:15:13

标签: knockout.js

使用knockout.js 我有一个复选框列表,当我检查项目时,它将添加到另一个复选框列表项目。我是指从列表到另一个复选框的所有选中项目。其次,当我取消选中第二个列表项时,它将删除当前表单并取消选中父项。

jsfiddle.net/pLNdc/90/

HTML

<div id="timetable">
    <ul class="calendar-short select-time" data-bind="template: { foreach: results }, style: { display: results().length > 0 ? 'block' : 'none' }">       
        <li>
            <input type="checkbox" class="css-checkbox" data-bind="value: id, checked: $parent.selectedChoices, attr: { id: 'timetable_' + id }">
            <label class="checkbox" data-bind="text: name, attr: { 'for': 'timetable_' + id }"></label>
        </li>
    </ul>
</div>

<div id="timetable">
    <ul class="calendar-short select-time" data-bind="template: { foreach: results1 }, style: { display: results().length > 0 ? 'block' : 'none' }">       
        <li>
            <input type="checkbox" class="css-checkbox" data-bind="value: id, checked: $parent.selectedChoices, attr: { id: 'timetable_' + id }">
            <label class="checkbox" data-bind="text: name, attr: { 'for': 'timetable_' + id }"></label>
        </li>
    </ul>
</div>
<div data-bind="text: selectedChoicesDelimited"></div>

的Javascript

var anil = {
    results: ko.observableArray([{
        'id': 1,
            'name': 'anil'
    }, {
        'id': 2,
            'name': 'akash'
    }]),
    selectedChoices: ko.observableArray([]),
    results1:ko.observableArray([])
}
anil.selectedChoicesDelimited = ko.dependentObservable(function () {            
            anil.results1 = ko.observableArray(anil.selectedChoices());        
            return anil.results1();
        });   

ko.applyBindings(anil);

1 个答案:

答案 0 :(得分:2)

尝试这样的事情

您需要根据所选复选框查询results并将object推送到results2数组以获取绑定名称&amp; id分别来查看。

viewModel:

var anil = {
    results: ko.observableArray([{
        'id': 1,
            'name': 'anil'
    }, {
        'id': 2,
            'name': 'akash'
    }]),
    selectedChoices: ko.observableArray([]),
    results1:ko.observableArray([])
}

anil.selectedChoicesDelimited = ko.dependentObservable(function () {
  anil.results1([]);
   ko.utils.arrayForEach(anil.selectedChoices(), function (item1) {
     ko.utils.arrayForEach(anil.results(), function (item2) {
        if (item2.id == item1) {
            anil.results1.push(item2);
        }
      });
   });
}); 

ko.applyBindings(anil);

查看:

<div id="timetable">
    <ul class="calendar-short select-time" data-bind="template: { foreach: results1 }, style: { display: results().length > 0 ? 'block' : 'none' }">       
        <li>
            <input type="checkbox" class="css-checkbox" data-bind="value: $data, checked: $parent.selectedChoices, attr: { id: 'timetable_' + $data }"/>
            <label class="checkbox" data-bind="text: name, attr: { 'for': 'timetable_' + $data }"></label>
        </li>
    </ul>
</div>
<div data-bind="text: selectedChoicesDelimited"></div>

工作样本小提琴here