Search code examples
ractivejs

Binding boolean values to radio buttons


When I bind a boolean variable to radio buttons with true/false values, the radio buttons' checked status does not get set when the template first loads -- both remain unchecked.

new Ractive({
    template: "#template",
    el: "#output",
    data: {
        accept: true
    }
});
<script src="//cdn.ractivejs.org/latest/ractive.js"></script>
<div id="output"></div>
<script id="template" type="text/html">
    <input type="radio" name="{{ accept }}" value="true" /> Yes
    <input type="radio" name="{{ accept }}" value="false" /> No
    <br/>
    accept = {{ accept }}
</script>

But once I click the radio buttons, their checked statuses do become in sync with the boolean variable.

How can I get this binding to work? Is it a bug with Ractive or am I doing something wrong?

I can work around the problem by changing my boolean variable to a string (accept: "true") but that really wouldn't be ideal.


Solution

  • Computed property will be an overkill for this case. Actually, you were close enough on your original example. Just try the following (only change is at value="{{true}}" instead of value="true"):

    new Ractive({
        template: "#template",
        el: "#output",
        data: {
            accept: false
        },
    });
    <script src="//cdn.ractivejs.org/latest/ractive.js"></script>
    <div id="output"></div>
    <script id="template" type="text/html">
        <input type="radio" name="{{ accept }}" value="{{true}}"/> Yes
        <input type="radio" name="{{ accept }}" value="{{false}}"/> No
        <br/>
        accept = {{ accept }}
        <button on-click="toggle('accept')">toggle</button>
    </script>