Alex Rivera | Logout

Set the selected item in a select list based on template value

Asked 2012-08-25T17:38:45.053
13

How can you correctly pre-populate a select control with the current value from the template?

I have a simple form to edit a record where the values for the selected record are pre-populated when the form is shown. A bit like this:

<input type="text" id="project_name_edit" value="{{selected_name}}">

But where I am using a select control I need to be able to interogate the template value and conditionally set the selected='selected' property for the correct option.

<select id="project_status_edit" value="{{selected_status}}">
      <option>GOOD</option>
      <option>BAD</option>
      <option>UGLY</option>
</select>

handlesbars.js offers the #IF helper but this only gives truthy or falsy.

I could probably hack this in various way but this seems like a scenario where there would be a standard solution.

Edit
Report

1 Answer

16

You can use a helper:

Handlebars.registerHelper('selected', function(foo, bar) {
  return foo == bar ? ' selected' : '';
});

Which you can then call with:

<select id="project_status_edit">
  <option{{selected foo "GOOD"}}>GOOD</option>
  <option{{selected foo "BAD"}}>BAD</option>
  <option{{selected foo "UGLY"}}>UGLY</option>
</select>

Using:

{"foo":"UGLY"}

Try it here:

http://tryhandlebarsjs.com/

Although it doesn't appear to let me save it. :(

answered 2012-08-25T18:32:12.563

Your Answer