[英]Knockout.js binding radio group does not work
I feel really stupid but can't make it work :)我觉得真的很愚蠢,但无法让它发挥作用:)
http://jsfiddle.net/btkmR/ http://jsfiddle.net/btkmR/
I made this simple Fiddle just to prove that I'm not missing something in my big project.我制作了这个简单的 Fiddle 只是为了证明我在我的大项目中没有遗漏任何东西。
HTML: 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: 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..我希望看到
Cherry
在开始时被选中。
From Knockout's documentation ( http://knockoutjs.com/documentation/checked-binding.html ):从 Knockout 的文档( 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.
对于单选按钮,当且仅当参数值等于单选按钮节点的 value 属性时,KO 才会设置要检查的元素。
Example: http://jsfiddle.net/btkmR/2/示例: 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
.对于那些像我一样正在努力使其与动态绑定的无线电组名称和值一起工作的人,请注意
data-bind
的绑定顺序。
Following will NOT work, as value
and name
are bound after checked
:以下将不起作用,因为
value
和name
在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
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.
如果您将 observable 值更新为“1”(数字作为字符串),则它可以工作。 Not very convenient...
不是很方便...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.