Keith
Keith

Reputation: 21244

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.

Upvotes: 3

Views: 4529

Answers (2)

pembeci
pembeci

Reputation: 705

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>

Upvotes: 5

Leakim
Leakim

Reputation: 616

To my knowledge, ractive types everything hard coded in the template value props of inputs to strings. Illustrated here.

However properties in your data-object does obviously retain their types. Usually multiple different values is what you use radio buttons for anyways. A simple "true/false" bool doesn't need more than a checkbox. Ugly example of binding your radio buttons to bool objects here. (PS: Obviously not recommended).

Upvotes: 0

Related Questions