I'm trying to render a select element with options, like this
<select dropdown multiple class="dropdown" name="color">
{{#each colors}}
<option value="{{value}}" {{isSelected parentColor id}}>{{title}}></option>
{{/each}}
</select>
I'm using the following handlebars helper
Handlebars.registerHelper('isSelected', function(input, color) {
return input === color ? 'selected' : '';
});
The problem is that the selected
attribute doesn't show up on any of the option
element, but when I place a console.log
in the handlebar helper I do see that one matches (input === color === true). Any ideas what I do wrong here ?
This is a working example of what is described,
hbs
<h1>Handlebars JS Example</h1>
<script id="some-template" type="text/x-handlebars-template">
<select dropdown multiple class="dropdown" name="color">
{{#each colors}}
<option value="{{value}}" {{isSelected parentColor id}}>{{title}}</option>
{{/each}}
</select>
</script>
js
var source = $("#some-template").html();
var template = Handlebars.compile(source);
var data = {
colors: [
{id:1,value:1,title:"red",parentColor:2},
{id:2,value:2,title:"green",parentColor:2},
{id:3,value:3,title:"blue",parentColor:1}
]
};
Handlebars.registerHelper('isSelected', function (input, color) {
return input === color ? 'selected' : '';
});
$('body').append(template(data));
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.