Displaying a Select Option as Selected Coming from a Database.

1 min read

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.

1Template.registerHelper('selectOption', function(option, value) {
2 if (option == value) {
3 return 'selected'
4 }
1{% raw %}
2<div class="controls">
3 <select class="form-control" name="type" id="type" value="{{marker.type}}">
4 <option value=""></option>
5 {{#each types}}
6 <option {{selectOption marker.type this._id}} value="{{_id}}">{{type}}</option>
7 {{/each}}
8 </select>
10{% 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!