Reputation: 17915
I feel really stupid but can't make it work :)
I made this simple Fiddle just to prove that I'm not missing something in my big project.
HTML:
<div>
Preferred flavor
<div><input type="radio" name="flavorGroup" data-bind="checked: cherryOn" /> Cherry</div>
<div><input type="radio" name="flavorGroup" data-bind="checked: almondOn" /> Almond</div>
<div><input type="radio" name="flavorGroup" data-bind="checked: mgOn" /> Monosodium Glutamate</div>
</div>
JS:
var viewModel = {
cherryOn: ko.observable(true);
almondOn: ko.observable(false);
mgOn: ko.observable(false);
};
ko.applyBindings(viewModel);
I expect to see Cherry
selected on start..
Upvotes: 9
Views: 9272
Reputation: 1054
I had a very interesting issue as well. If your radio input values are numbers and you have integers in your model observables - no radio button will get selected. If you update observable value to be "1" (number as string), then it works. Not very convenient...
Upvotes: 0
Reputation: 3332
For those who, like me, are struggling to get it working with dynamically bound radio group name and values, pay attention to order of bindings in the data-bind
.
Following will NOT work, as value
and name
are bound after checked
:
<input
type="radio"
data-bind="
checked: $parent.correctAnswerId,
attr: {name: 'correctAnswerFor' + $parent.id, value: id}
"
/>
correct order is :
attr: {name: 'correctAnswerFor' + $parent.id, value: id},
checked: $parent.correctAnswerId
Upvotes: 13
Reputation: 792
From Knockout's documentation (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.
Example: http://jsfiddle.net/btkmR/2/
<div>
Preferred flavor
<div><input type="radio" name="flavorGroup" value="cherry" data-bind="checked: flavor" /> Cherry</div>
<div><input type="radio" name="flavorGroup" value="almond" data-bind="checked: flavor" /> Almond</div>
<div><input type="radio" name="flavorGroup" value="Monosodium" data-bind="checked: flavor" /> Monosodium Glutamate</div>
</div>
var viewModel = {
flavor: ko.observable("cherry")
};
ko.applyBindings(viewModel);
Upvotes: 22