Ich habe ein Beispiel, das 2 Kontrollkästchen enthält. Ich möchte sicherstellen, dass immer 1 Checkbox aktiv ist, dh entweder Checkbox 1 oder Checkbox 2 oder beide können aktiv sein. Wie kann ich das machen?Wie erstellt man eine Liste von Kontrollkästchen, wo mindestens 1 Box aktiv ist
function DemoItem(id, name) {
var self = this;
self.id = ko.observable(id);
self.Name = ko.observable(name);
self.Selected = ko.observable(false);
}
function ViewModel() {
var self = this;
self.availableItems = ko.observableArray();
self.associatedItemIds = ko.observableArray();
self.init = function() {
self.availableItems.push(new DemoItem(1, 'One'));
self.availableItems.push(new DemoItem(2, 'Two'));
};
self.toggleAssociation = function (item) {
if (item.Selected() === true) console.log("dissociate item " + item.id());
else console.log("associate item " + item.id());
item.Selected(!(item.Selected()));
return true;
};
}
var viewModel = new ViewModel();
ko.applyBindings(viewModel);
viewModel.init();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.2.0/knockout-min.js"></script>
Available Items:
<div data-bind="foreach: $root.availableItems">
<input type="checkbox" data-bind="value: id(), checked: $root.associatedItemIds, click: $root.toggleAssociation" /> \t
<span data-bind="text: ' ' + Name()"></span>
<br/>
</div>
<br/>
Associated Item Ids:
<div data-bind="foreach: $root.associatedItemIds">
<span data-bind="text: $data"></span>
<br/>
</div>