Dependent Select

I’m trying to create a simple dependent select. I’ve seen several articles, including this one, but I keep thinking there HAS to be a “right” way to do this reactively.

I’m not using widgets, just plain HTML select elements. The first is for Species, that pulls from a Species Mongo collection. The second is for Breeds - a separate collection. Both are rendered from Templates. I can get the Species and then handle the change event, but I have no clue where to go from there.

I also saw this SO post, but the answer isn’t marked as right and the API looks a tad deprecated.

Can someone point me in the right direction here?

HTML

<template name="speciesSelect">
  <select id="species" class="pure-u-23-24">
  {{#each species}}
    <option value="{{_id}}">{{name}}</option>
  {{/each}}
  </select>
</template>

<template name="breedsSelect">
  <select id="primary-breed" class="pure-u-23-24">
  {{#each breed}}
    <option>{{name}}</option>
  {{/each}}
  </select>
</template> 

#JS

Species = new Mongo.Collection("species");
Breeds = new Mongo.Collection("breeds");

Template.speciesSelect.helpers({
  species: function() {
    return Species.find();
  }
});

Template.speciesSelect.events({
  "change #species": function(e) {
    // now what the heck to I do?
  }
});

Not tested:

<template name="select">

  <select id="species" class="pure-u-23-24">
    {{#each species}}
      <option value="{{_id}}">{{name}}</option>
    {{/each}}
  </select>

  <select id="breed" class="pure-u-23-24">
    {{#each breeds}}
      <option value="{{_id}}">{{name}}</option>
    {{/each}}
  </select>

</template>
Template.select.created = function() { 
 this.selSpecies = new ReactiveVar(null);
}

Template.select.helpers({
  species: function() {
    return Species.find();
  },

  breeds: function() {
    var speciesId = Template.instance().selSpecies.get();
    return speciesId ? Breeds.find({ speciesId: speciesId }) : null;
  }
});

Template.select.events({
  'change #species': function(event, instance) {
    var speciesId = $(event.target).val();
    instance.selSpecies.set(speciesId);
  }
});
1 Like

This is more or less the answer, only I did roughly the same thing with Session vars which are reactive.

Much thanks!