Knockout.js radio communication group not working

I feel really stupid, but can't make it work :)

http://jsfiddle.net/btkmR/

I made this simple script just to prove that in my big project I am not losing anything.

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 at startup.

+6
source share
2 answers

From the knockout documentation ( http://knockoutjs.com/documentation/checked-binding.html ):

For switches, KO sets the element to be checked if and only if the parameter value is equal to the value of the node s attribute of the radio book.

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); 
+16
source

For those who, like me, are struggling to get him to work with the dynamically linked name and values ​​of a group of radio stations , pay attention to the order of bindings in the data-bind .

Below will NOT work, since value and name are linked after checked :

 <input type="radio" data-bind=" checked: $parent.correctAnswerId, attr: {name: 'correctAnswerFor' + $parent.id, value: id} " /> 

correct order:

  attr: {name: 'correctAnswerFor' + $parent.id, value: id}, checked: $parent.correctAnswerId 
+11
source

All Articles