I'm using a template binding to render a set of radio buttons. There is also a css binding on the element.
When a radio button is clicked, the viewmodel & view are are updated, but the checked state of the radio button is lost. Is there a work around for this?
<div data-bind="with: point">
<div data-bind="template: { name: 'template1', data: $data }, css: { 'has-warning': hasAlarm }"></div>
</div>
<script type="text/template" id="template1">
<!-- ko foreach: choices -->
<label>
<input type="radio" data-bind="checked: $parent.value, value: $data" name="test" />
<span data-bind="text: $data"></span>
</label><br/>
<!-- /ko -->
<span data-bind="visible: hasAlarm">Abnormal!</span>
</script>
The problem is with the order of the checked
and value
bindings. The checked
binding uses the element's value to determine whether it should be checked or not. When the element is first bound, the value is set by the value
binding after the checked
binding is initialized. So the simplest fix is to re-order the bindings. Also I'd suggest you use the attr
binding instead of value
since value
has extra overhead (it's a two-way binding designed for text boxes).
data-bind="attr: {value: $data}, checked: $parent.value"
http://jsfiddle.net/mbest/d3YJc/2/
Knockout 3.0 fixes the order problem also (in addition to the rendering issue mentioned in the comments), so that's another way to solve this.