demo
demo

Reputation: 6235

Knockout binding to radio box

I have radio box. For that I have binded click event. Problem : In case this radio box should be checked from start - it isn't.

So I want to add checked event. But this will brake click logic, so it will looks like double click.

How can I correctly bind all events to radio without manually calling click when my ViewModel is created?

<input data-bind="css: { checked: $component.isActiveGroup(value) },
                              click: $component.setActiveGroup.bind($component, value), 
                              checked: $component.activeGroup"
                   value={{value}}
                   type="radio" />

setActiveGroup(groupName: string) {
    if (!groupName) {
        return;
    }
    const isActive = this.isActiveGroup(groupName);
    this.activeGroup(isActive ? '' : groupName);
}

isActiveGroup(groupName: string) {
    return this.activeGroup() === groupName;
}

activeGroup = ko.observable('');

Upvotes: 2

Views: 52

Answers (1)

user3297291
user3297291

Reputation: 23372

The checked binding does everything you need by default:

var VM = function() {

  this.activeGroup = ko.observable("A");
  this.activeGroup.subscribe(console.log.bind(console));

  this.isActiveGroup = groupName => {
    return this.activeGroup() === groupName;
  }


  this.groups = ["A", "B", "C"];
}


ko.applyBindings(new VM());
.checked { background: yellow; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.2.0/knockout-min.js"></script>

<!-- ko foreach: groups -->
<label data-bind="css: { checked: $parent.isActiveGroup($data) }">
  <span data-bind="text: $data"></span>
  <input type="radio" data-bind="value: $data,
                                 checked: $parent.activeGroup" />
</label>
<!-- /ko -->

If you're looking for "toggle" functionality, you should create either type="checkbox" inputs or create an additional option none. Radio boxes are meant to have 1 selection per group.

P.S. to style the checked input, you can also use the :checked css selector. In my example, I chose to style the surrounding label.

Upvotes: 1

Related Questions