I'm trying to use mustache templates to render very simple forms, however, one of the forms has a collection of radio buttons. I can't figure out how to have the right radio button selected when the form is rendered.
Is this something that is simple and I'm just missing something, or does the "logic-less" aspect of mustache really prevent me rending something as basic as a radio button?
My data looks something like this:
data = { gender: 'female' }
<form>
<label><input type="radio" name="gender" value="male"> Male</label>
<label><input type="radio" name="gender" value="female"> Female</label>
</form>
You can do this using a lambda:
var data = {
gender: 'female',
wrapped: function () {
return function (text) {
return text.replace('value="' + this.gender+'"', 'value="' + this.gender+'" checked');
}
}
};
<form>
{{#wrapped}}
<label><input type="radio" name="gender" value="male"> Male</label>
<label><input type="radio" name="gender" value="female"> Female</label>
{{/wrapped}}
</form>
Have a look at the full example I used if you have any trouble.
Update:
Justin Hileman showed me another way of doing this:
<form>
<label><input type="radio" name="gender" value="male"{{#maleIsDefault}} checked{{/maleIsDefault}}>
Male</label>
<label><input type="radio" name="gender" value="female"{{#femaleIsDefault}} checked{{/femaleIsDefault}}> Female</label>
</form>
var data = {
gender: 'female',
maleIsDefault: function() {
return this.gender == 'male';
},
femaleIsDefault: function() {
return this.gender == 'female';
}
};
Full example here.
Another option, with coffeescript (untested)...
// define radio button options in an array
genders = [
{ code: 'M', name: 'Male' }
{ code: "F", name: "Female" }
]
// flag the current object as "selected"
for g in genders
if g.code == existingGenderValue
g.selected = true
Then in mustache, dynamically generate your buttons based on the genders array:
{{#genders}}
<label class="radio">
<input type="radio" name="gender" value="{{code}}" {{#selected}} checked="checked" {{/selected}}>
{{name}}
</label>
{{/genders}}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With