I feel really stupid but can't make it work :)
http://jsfiddle.net/btkmR/
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..
Binding Values The binding value can be a single value, literal, a variable or can be a JavaScript expression.
A binding consists of two items, the binding name and value, separated by a colon. Here is an example of a single, simple binding: Today's message is: <span data-bind= "text: myMessage" ></span> An element can include multiple bindings (related or unrelated), with each binding separated by a comma.
KO is able to create a two-way binding if you use value to link a form element to an Observable property, so that the changes between them are exchanged among them. If you refer a simple property on ViewModel, KO will set the form element's initial state to property value.
An observable is useful in various scenarios where we are displaying or editing multiple values and require repeated sections of the UI to appear and disappear as items are inserted and deleted. The main advantage of KO is that it updates our UI automatically when the view model changes.
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);
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
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