devgen
devgen

Reputation: 31

knockout checked binding - only one checked

I have a list of Admins with a check box. I want to be able to select only one Admin.

HTML:

<tbody data-bind="foreach: people">
<tr>
 <td>
   <input type="checkbox" data-bind="attr: { value: id }, checked: $root.selectedAdmin">
    <span data-bind="text: name"/>
</td>
</tr>
</tbody

JS:

function Admin(id, name) {
    this.id = id;
    this.name = name;
}

var listOfAdmin = [
new Admin(10, 'Wendy'),
new Admin(20, 'Rishi'),
new Admin(30, 'Christian')];

var viewModel = {
    people: ko.observableArray(listOfAdmin),
    selectedAdmin: ko.observableArray()
};

ko.applyBindings(viewModel);

For Example if Admin id 10 is selected the other admins should be deselected.

Is that Possible to do with Knockout?

Upvotes: 3

Views: 3054

Answers (1)

nemesv
nemesv

Reputation: 139748

You should really use radio buttons if you only want to allow multiple selection.

However if you still want to use checkboxes then on solution would be to combine the checked and the click binding:

Use the checked to check only when the current id equal to the selectedAdmin property and use the click binding to set the selectedAdmin.

So you HTML should look like this:

<input type="checkbox" data-bind="attr: { value: id }, 
                                  checked: $root.selectedAdmin() == id, 
                                  click: $parent.select.bind($parent)" />

And in your view model you just need to implement the select function:

var viewModel = {
    people: ko.observableArray(listOfAdmin),
    selectedAdmin: ko.observableArray(),
    select: function(data) {
        this.selectedAdmin(data.id);
        return true;
    }
};

Demo JSFiddle.

Notes:

  • the return true; at the end of the select function. This is required to trigger the browser default behavior in this case to check the checkbox.
  • the .bind($parent) is needed to set the this in the select function to be the "parent" viewModel object.

Upvotes: 4

Related Questions