Search code examples
javascriptmongodbmeteormeteor-blazespacebars

Meteor Select Box - mark option as selected depending on data context


I have been trying to figure out how to set the 'selected' attribute on an option within a select box and have fallen short today. Any help would be appreciated.

What I'm trying to accomplish: When a user chooses an option and hits submit, the data saves to a new mongo document and the new entry is shown on the screen (this part works). Upon browser refresh, the state is lost (due to no selected attribute being set) and the select box goes back to the first option. I need to figure out how to set the selected state depending on the value the user has saved on that particular document. On this page there are many of the same select boxes allowing the user to choose different options for other entries.

References (tried to implement with no luck):

  1. Check for equality in Spacebars?

  2. https://github.com/meteor/meteor/wiki/Using-Blaze#conditional-attributes-with-no-value-eg-checked-selected

  3. How do I indicate 'checked' or 'selected' state for input controls in Meteor (with spacebars templates)?

select box template:

<template name="tEdit">
<div class="form-group">
  <div class="controls">
    {{> fFEdit}}
  </div>
</div>
</template>

select box option template:

<template name="fFEdit">
  <select class="form-control" name="fFSelect">
    {{#each fFSelect}}
      <option value="{{fId}}">{{fF}}</option>
    {{/each}}
  </select>
</template>

setting data context

Template.fFEdit.helpers({
  fFSelect: function() {
    var fFArray = [
      { fF: "foo", fId: 0 },
      { fF: "bar", fId: 1 },
      { fF: "buzz", fId: 2 }
    ];
    return fFArray;
  }
});

Solution

  • I'm not sure if this is the best answer to my problem, though this is what I came up with to add the selected attribute to the saved option. I welcome anyone else with a better/Meteor solution for this.

    When the user clicks the edit link, I find the inputs that need to be updated and assign the values onClick. Ideally I'd rather have this already done on pageLoad, though feel that that solution may impact the initial pageLoad time.

    Template.tItem.events({
      'click .edit-t-item': function(e) {
        e.preventDefault();
    
        var $editTWrapper = $(e.currentTarget).next('.edit-t-wrapper');
        $editTWrapper.find('[name=tNEdit]').val(this.tName);
        $editTWrapper.find('[name=fFSelect]').val(this.fFId);
      }
    });