mardi 26 avril 2016

How to create a list of checkbox where at least 1 box is active

I have an example that contains 2 checkbox. I would like to make sure that there is always 1 checkbox is active, it means either checkbox 1 or checkbox 2 or both of them can be active. How can I do that?

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="http://ift.tt/Zv5K7g"></script>
<script src="http://ift.tt/1sl7oHg"></script>
Available Items:
<div data-bind="foreach: $root.availableItems">
    <input type="checkbox" data-bind="value: id(), checked: $root.associatedItemIds, click: $root.toggleAssociation" />   
    <span data-bind="text: '&nbsp;' + Name()"></span>
    <br/>
</div>
<br/>
Associated Item Ids:
<div data-bind="foreach: $root.associatedItemIds">
    <span data-bind="text: $data"></span>
    <br/>
</div>



Aucun commentaire:

Enregistrer un commentaire