I need, based on the json array "option" to populate an select field
My Script look like this:
var option = [
{"mod":"A","values":
{"Field":"A","Value":"101"}
},
{"mod":"B","values:
{"Field":"B","Value":"102"}},
{"mod":"C","values"
{"Field":"C","Value":"99"}
},
{"mod":"D","values":
{"Field":"D","Value":"96"}
}];
var theTemplateScript = $('#shoe-template').html();
var theTemplate = Handlebars.compile(theTemplateScript);
$('.shoesNav').append(theTemplate(option));
and my html is as follow:
<script id="shoe-template" type="x-handlebars-template">
{{#each option}}
<option value="{{values.Value}}">
{{values.Field}}
</option>
{{/each}}
</script>
<select class="shoesNav">
</select>
I don't have any console error, however the field is not being populated, what am I missing ?
You need to namespace the data object with the key in the {{#each option}}
loop, which in this case is option
. Here's a working implementation:
var namespace = 'option'; var data = {}; data[namespace] = [{ "mod": "A", "values": { "Field": "A", "Value": "101" } }, { "mod": "B", "values": { "Field": "B", "Value": "102" } }, { "mod": "C", "values": { "Field": "C", "Value": "99" } }, { "mod": "D", "values": { "Field": "D", "Value": "96" } }]; var theTemplateScript = $('#shoe-template').html(); var theTemplate = Handlebars.compile(theTemplateScript); $('.shoesNav').append(theTemplate(data));
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.0.2/jquery.min.js"></script> <script src="https://cloud.github.com/downloads/wycats/handlebars.js/handlebars-1.0.0.beta.6.js"></script> <script id="shoe-template" type="x-handlebars-template"> {{#each option}} <option value="{{values.Value}}"> {{values.Field}} </option> {{/each}} </script> <select class="shoesNav"> </select>
I hope that helps.
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.