Red Devil Red Devil - 7 months ago 13
Javascript Question

Knockout JS Radio buttons selecting last button if all values are true

What I am trying to do is show some radio buttons with data from the server. The problem is that the checked value for the radio buttons can be all false and then KO automaticaly selects the last radio button just like in the JS fiddle that I have created below. This works perfectly as intended if one of the values is true but in my case there is a high chance that these values will all be false.

https://jsfiddle.net/9mtzbmng/1/

self.addItems = function (items) {
for (var x in items)
{
self.Items.push(new Item(items[x]));
}
}
function Item(items) {
this.ID = items.ID;
this.Checked = ko.observable(false);
}

<input type="radio" data-bind="value: $data.ID,checked: Checked, checkedValue: Checked" name="items">


EDIT:
https://jsfiddle.net/hrhuym0u/
My issue was fixed after following this jsfiddle by setting the
checkedValue: 'true'
and setting
this.Checked = ko.observable("false")
!

Answer

From the documentation:

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

In your case you need to set checkedValue to true so when your Checked observable contains true only then it checks your radio button:

<input type="radio" name="radioB" data-bind="value: $data.ID, 
                                             checked: Checked, 
                                             checkedValue: true">

Demo https://jsfiddle.net/r6njzje3/

Note: if your radio buttons have the same name then they are forming a group so only one of them can be checked, that is way in your original sample always the last one is checked. Because the checked always equals with the value of checkedValue. So if you would remove the name name="radioB" all of your radios would be checked.

Note 2: You should make sure that you have actual boolean values in your Checked properties and your server does not send them as strings e.g. "true", because in this case you also need to specify the checkedValue as a string:

<input type="radio" name="radioB" data-bind="value: $data.ID, 
                                             checked: Checked, 
                                             checkedValue: 'true'">

Demo: https://jsfiddle.net/hrhuym0u/