Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 818
devgen Avatar asked Nov 20 '25 03:11

devgen


1 Answers

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.
like image 200
nemesv Avatar answered Nov 22 '25 16:11

nemesv



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!