plamtod
plamtod

Reputation: 79

Knockout radio button check binding

I have ViewModel in which I have array of "Answers". "Answer" is object that has property 'Selected'. In my demo array I have two Answers. For first Selected=1 and for second Selected=0. I have no idea why both radio buttons are selected. Here is my demo link - https://jsfiddle.net/jwoscjot/3/ and my binding is

<input type="radio"  data-bind=" value: Selected, checked: Selected">

Upvotes: 2

Views: 2157

Answers (1)

CrimsonChris
CrimsonChris

Reputation: 4641

From http://knockoutjs.com/documentation/checked-binding.html

For radio buttons, KO will set the element to be checked if and only if the parameter value equals the radio button node’s value attribute or the value specified by the checkedValue parameter.

You should consider adding a selectedAnswerID property to your view model.

<!-- ko foreach: answers -->
    <input type="radio" data-bind="value: answerID, checked: $parent.selectedAnswerID">
<!-- /ko -->

If you really want to keep the answer's selected state a part of the answer, then you can used the checkedValue part of the binding. Note that you won't have a way to "deselect" an answer unless you provide some sort of "clear" button because radio buttons aren't really intended to support multi-select.

<!-- ko foreach: answers -->
    <input type="radio" data-bind="checked: selected, checkedValue: 1">
<!-- /ko -->

Upvotes: 1

Related Questions