Displaying a Select Option as Selected Coming from a Database.

I was creating an edit page last week where I needed a select element option to be displayed based on the value saved in the database. I struggled with this problem, but eventually created a solution, and learned a lot from it! My solution was to use a Template.registerHelper.

Templates have helpers that are template specific naturally. I decided to create a global template helper using Template.registerHelper that would add the attribute selected to an option if it’s value matched the value in the database.

Template.registerHelper("selectOption", function (option, value) {
  if (option == value) {
    return "selected";
  }
});
{% raw %}
<div class="controls">
  <select class="form-control" name="type" id="type" value="{{marker.type}}">
    <option value=""></option>
    {{#each types}}
      <option
        {{selectOption marker.type this._id}}
        value="{{_id}}"
      >{{type}}</option>
    {{/each}}
  </select>
</div>
{% endraw %}

My template helper selectOption takes two parameters to compare. If the parameters match, then selected is returned. In my template I use this helper just like any other helper with {% raw %}{{selectOption}}{% endraw %}. I am passing in the value in the database (marker.type) and the ID of the type I’m iterating over in my {%raw%}{{each}}{%endraw%} block helper. Because I’m storing the ID of the marker.type in my database, I simple compare it to the ID of the type I’m iterating over. This works perfectly.

Hope this helps!