With a Handlebars.js template like this...
@lazd's answer does not work for elements within an
.
selectedIndex
is numbered monotonically for all s, but
select.children
holds the s, and
select.children[n].children
holds the s within
n (with numbering restarting within each
, of course).
This alternative version will work for elements within
s:
Handlebars.registerHelper('select-optgrp', function(value, options) {
var select = document.createElement('select'); // create a select element
select.innerHTML = options.fn(this); // populate it with the option HTML
select.value = value; // set the value
var g = 0, i = select.selectedIndex; // calculate which index of which optgroup
while (i >= select.children[g].children.length) { i -= select.children[g].children.length; g++; }
if (select.children[g].children[i]) { // if selected node exists add 'selected' attribute
select.children[g].children[i].setAttribute('selected', true);
}
return select.innerHTML;
});