Handlebars: Create a select element and populate with options
HTML
<script src="https://cdnjs.cloudflare.com/ajax/libs/handlebars.js/4.0.10/handlebars.min.js"></script>
<script src="https://code.jquery.com/jquery-2.2.4.min.js"></script>
<h2>Handlebars template to create a select element and populate with options</h2>
<div id="myForm"></div>
<!-- The script element is used to define the Handlebars template -->
<script type="text/handlebar-template" id="selectPersonTemplate">
<span>Select a Person: </span>
<select id="person">
{{#each people}}
<option value="{{id}}">{{firstName}} {{lastName}}</option>
{{/each}}
</select>
</script>
<div style="position: absolute;bottom: 5px;">
Read about this Fiddle at: <a href="http://jsdev.wikidot.com/howto:11" target="_blank">How To: Handlebars - Iterate over Arrays with the Each Helper</a>
</div>
JavaScript
$(function () {
// Define an array of people.
var people = [
{ id: 1, firstName: "Anthony", lastName: "Nelson" },
{ id: 2, firstName: "Helen", lastName: "Garcia" },
{ id: 3, firstName: "John", lastName: "Williams" }
];
// Get the text for the Handlebars template from the script element.
var templateText = $("#selectPersonTemplate").html();
// Compile the Handlebars template.
var selectPersonTemplate = Handlebars.compile(templateText);
// Evaluate the template with an array of people.
var html =
({ people: people });
// Take the HTML that was created with the Handlebars template and
// set the HTML in the myForm div element.
$("#myForm").html(html);
});