I have two radio buttons.
<td>
<div style="display: inline; margin-right: 10px">
<input type="radio" name="USGlobalUser" data-bind:"checked:IsGlobal/>US
</div>
<div style="display: inline">
<input type="radio" name="USGlobalUser" data-bind:"checked:IsGlobal"/>Global
</div>
</td>
I am populating my model like this
QuestionnaireModel = function (data) {
self.IsGlobal = ko.protectedObservable(data ? data.IsGlobal : false);
}
The value is coming from DB perfectly and its getting populated in self.IsGlobal as true/false. Based upon this true/false, I want to set my radio button checked.
The checked binding works differently for radio buttons:
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. So, your parameter value should be a string.
So your IsGlobal
should hold a string and you need to have the same string as the value of the radio buttons:
<input type="radio" name="USGlobalUser"
data-bind="checked: IsGlobalCheckbox" value="false" />US
<input type="radio" name="USGlobalUser"
data-bind="checked: IsGlobalCheckbox" value="true" />Global
And in your viewmodel:
self.IsGlobal = ko.observable(data ? data.IsGlobal + "" : "false");
If you want to keep the IsGlobal
to store a boolean value you need to create a new computed property for the radio button which does the conversion:
self.IsGlobalCheckbox = ko.computed({
read: function() {
return self.IsGlobal() + "";
},
write: function (v) {
if (v == "true") self.IsGlobal(true)
else self.IsGlobal(false)
}
});
Demo JSFIddle.
And by the way as Tomas noted your binding systax is broken in your sample.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With