janjarfalk janjarfalk - 4 months ago 114
Javascript Question

How to set selected select option in Handlebars template

With a Handlebars.js template like this...

<select>
<option value="Completed">Completed</option>
<option value="OverDue">OverDue</option>
<option value="SentToPayer">SentToPayer</option>
<option value="None">None</option>
</select>


... and data like this...

{
"id" : 1,
"name" : "World"
"status" : "OverDue",
"date" : "2012-12-21"
}


I want to render HTML like this.

<select>
<option value="Completed">Completed</option>
<option value="OverDue" selected="selected">OverDue</option>
<option value="SentToPayer">SentToPayer</option>
<option value="None">None</option>
</select>


Which way is the easiest?

Answer

I found a lot of over complicated solutions and decided to write my own using a Handlebars helper.

With this partial (using Jquery) ...

    window.Handlebars.registerHelper('select', function( value, options ){
        var $el = $('<select />').html( options.fn(this) );
        $el.find('[value="' + value + '"]').attr({'selected':'selected'});
        return $el.html();
    });

You can wrap selects in your Handlebars template with {{#select status}}...

<select>
    {{#select status}}
    <option value="Completed">Completed</option>
    <option value="OverDue">OverDue</option>
    <option value="SentToPayer">SentToPayer</option>
    <option value="None">None</option>
    {{/select}}
</select>

and end up with this...

<select>
    <option value="Completed">Completed</option>
    <option value="OverDue" selected="selected">OverDue</option>
    <option value="SentToPayer">SentToPayer</option>
    <option value="None">None</option>
</select>

Presto!