Oliver Lloyd
Oliver Lloyd

Reputation: 5004

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.

Upvotes: 13

Views: 17521

Answers (5)

Yousef
Yousef

Reputation: 139

I used the following in my project (in case someone needs it :)

  <select class="form-control" id="maritalStatusList" >
      <option {{selectedMaritalStatus  "Single"}}> Single</option>
      <option {{selectedMaritalStatus  "Married"}}> Married</option>
  </select>

and

Template.editApplicant.helpers({
   selectedMaritalStatus: function(key){
      return key == this.maritalStatus ? 'selected' : '';
   }
});

"this.maritalStatus" gets the Marital Status from the current document (Applicant).

Use the following code, to save the value in the database

maritalStatus: $('#maritalStatusList').val()

Thanks for you all..

Upvotes: 4

I made this function. Adapt to your case

selectedOption=function(){
        selectedOpt=document.getElementById("yourTagId_Select");
        var att = document.createAttribute("selected");
        att.value = "selected";
        idObj=Session.get("idObj");
        var lib = yourCollection.find({'column._id':idObj}).fetch();      
        for (var i = 0; i < selectedOpt.length; i++) {
             if (selectedOpt[i].value==lib._id._str){               
                return selectedOpt[i].setAttributeNode(att);
            }
        };


    }

After call your function

selectedOption();

Upvotes: 1

bitspook
bitspook

Reputation: 669

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).

Upvotes: 11

Milosz Falinski
Milosz Falinski

Reputation: 47

I had almost an identical problem, but values I was passing were numbers and I believe I have a cleaner solution for that specific case, that is without depending on Handlebars magic.

In the template:

<select name="button-style" id="button-style" _val="{{button_style}}">
    <option value="1">Primary Style</option>
    <option value="2">Secondary Style</option>
</select>

you basically pass the number of the attribute you want selected with _val. This is useful only in a case where each option has a consecutive numerical value. Also note, if you name this attribute 'value', it will get overwritten/ignored by the default, which selects first option.

Now in the .rendered callback in your JS file:

Template.templateName.rendered = () ->
    var btn_style = $('#button-style').attr('_val')
    $('#button-style option:nth-child(' + btn_style + ')').attr('selected', 'selected')

This simply selects the 'nth' option in this select field which corresponds to the value we want.

Upvotes: 1

Jared Farrish
Jared Farrish

Reputation: 49208

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

Upvotes: 16

Related Questions