Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 279
Oliver Lloyd Avatar asked Aug 25 '12 17:08

Oliver Lloyd


2 Answers

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. :(

like image 56
Jared Farrish Avatar answered Sep 21 '22 05:09

Jared Farrish


The selected answer doesn't work anymore. It's an old question but I had a hard time figuring this simple thing out. Here's my solution:

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

In present version of meteor, we can't set HTML attributes without value, and meteor doesn't allow using {{#if}} either. But the objects passed to the helper are converted into key=value pairs and injected.

UPDATE

Use UI.registerHelper instead of Handlebars.registerHelper in new (> 0.8) versions of meteor since Handlebars namespace is depreciated (https://github.com/meteor/meteor/wiki/Using-Blaze#handlebars-namespace-deprecated).

like image 36
bitspook Avatar answered Sep 19 '22 05:09

bitspook