单击一个复选框时,防止将所有复选框设置为true / false

时间:2018-01-22 18:51:09

标签: javascript checkbox knockout.js

我在Knockout工作,我正在尝试在选中特定复选框时获取特定信息。但是,当我点击一个复选框时,正在发生的是选中/取消选中每个复选框。我的问题是,我如何防止这种情况发生并将其转移到只选中/取消选中我选择/取消选中的复选框的位置?

JS 我已将其简化为仅显示我正在使用的代码。

export class Model{
    isSelected: KnockoutObservable<boolean>;
    constructor(){
        this.isSelected = ko.observable(false);
    }
    selectStuff = () => {
        return true;
    }
}

HTML

<div data-bind="foreach: stuffToLoopThrough">
    <input type="checkbox" class="checkbox" name="checkBox" data-bind="checked: $root.isSelected, click: $root.selectStuff" />Send Stuff

    <input type="checkbox" class="checkbox" name="checkBox" data-bind="checked: $root.isSelected, click: $root.selectStuff" />Send Stuff

    <input type="checkbox" class="checkbox" name="checkBox" data-bind="checked: $root.isSelected, click: $root.selectStuff" />Send Stuff
</div>

所以这里发生的是,如果我点击三个复选框中的一个,将选中每个复选框,我只想选中我选中的复选框。我该如何做到这一点?我在哪里错了?

1 个答案:

答案 0 :(得分:0)

您想要选择多个值还是仅选择一个?如果你只想要1使用收音机而不是复选框。

无论哪种方式,请查看允许您将结果存储在变量中的checkedValue绑定:

http://knockoutjs.com/documentation/checked-binding.html

var stuffToLoopThrough = Model[];
var selectedValue = ko.observable();

    export class Model{
    isSelected: KnockoutObservable<boolean>;
    constructor(){
        this.uniqueValueOrId= ko.observable();
        this.isSelected = ko.observable(false);
    }
    selectStuff = () => {
        return true;
    }
}

然后是html

<div data-bind="foreach: stuffToLoopThrough">
    <input type="radio"
           class="radio" 
           name="checkBox" 
           data-bind="checked:  isSelected, 
           checkedValue: $root.uniqueValueOrId, 
           click: $root.selectStuff"> Send Stuff
</div>

注意我没有使用$ root来检查...