Question

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?

http://jsfiddle.net/d3YJc/1/

<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>
Was it helpful?

Solution

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top