How to set default value for HTML select element with Meteor?

How do you set the default value of a select box if the default value has already been chosen based on a collection. Right now I use plenty of meteor helper functions to check if each individual thing is selected. Is there a more effective or efficient way?

Ended up doing this - hope it helps someone out there!:

Template:

<template name="test">
  <select>
    <option selected="{{selectDeliveryStatus 'Waiting for supply'}}">Waiting for supply</option>
    <option selected="{{selectDeliveryStatus 'Being packaged'}}">Being packaged </option>
    <option selected="{{selectDeliveryStatus 'Sitting in inventory'}}">Sitting in inventory</option>
    <option selected="{{selectDeliveryStatus 'Dispatch'}}">Dispatch</option>
    <option selected="{{selectDeliveryStatus 'Delivered'}}">Delivered</option>
  </select>

</template>

Helper

Template.deliveryItem.helpers({
  selectDeliveryStatus: function(optionText){
    if(optionText === this.deliveryStatus){
      return 'selected'
    }
  }
})
2 Likes

Not everyone agrees with putting logic like this in the view but what I do is have a helper called isEqual and pass the two variables into it, so in your case it your template would look like:

<template name="test">
  <select>
    <option selected="{{isEqual deliveryStatus 'Waiting for supply'}}">Waiting for supply</option>
    <option selected="{{isEqual deliveryStatus 'Being packaged'}}">Being packaged </option>
    <option selected="{{isEqual deliveryStatus 'Sitting in inventory'}}">Sitting in inventory</option>
    <option selected="{{isEqual deliveryStatus 'Dispatch'}}">Dispatch</option>
    <option selected="{{isEqual deliveryStatus 'Delivered'}}">Delivered</option>
  </select>
</template>

Nothing in the controller, but you’d need to register a global helper:

Blaze.registerHelper('isEqual', function (lhs, rhs) {
    return lhs === rhs;
});

Edit: You can just return a true or false value for properties like selected, disabled and readonly.

2 Likes