With a Handlebars.js template like this...
I saw the extremely clever solution posted by @janjarfalk and realized it didn't work for options defined without a value attribute (such as ). My application needed that, and I wanted a helper done in vanilla JavaScript for performance, so I came up with the following.
This solution will support in addition to
and will be much faster as it doesn't use jQuery.
Handlebars.registerHelper('select', function(value, options) {
// Create a select element
var select = document.createElement('select');
// Populate it with the option HTML
select.innerHTML = options.fn(this);
// Set the value
select.value = value;
// Find the selected node, if it exists, add the selected attribute to it
if (select.children[select.selectedIndex])
select.children[select.selectedIndex].setAttribute('selected', 'selected');
return select.innerHTML;
});
Usage: