Cascading selects in Meteor
Tags : Meteor
This is a quick cascading select with collections. If you see any errors or recommendations please leave a comment.
#template html
<head>
<title>cascading_select</title>
</head>
<body>
<h1>Cascading select example</h1>
{{> cascade}}
</body>
<template name="cascade">
<select id="brands">
<option value="">Select Brand</option>
{{#each brands}}
<option value="{{name}}">{{name}}</option>
{{/each}}
</select>
<select id="models">
<option value="">Select Model</option>
{{#each models}}
<option value="{{name}}">{{name}}</option>
{{/each}}
</select>
</template>
#template js
Meteor.subscribe("Brands");
Meteor.subscribe("Models");
Template.cascade.helpers({
brands: function(){
return Brands.find();
},
models: function(){
return Models.find({brand: Session.get("brandSelected")})
}
});
Template.cascade.events({
"change #brands": function(e){
var brandSelected = $("#brands option:selected").val();
Session.set("brandSelected", brandSelected);
}
});
# collections
Brands = new Meteor.Collection("Brands");
Models = new Mongo.Collection("Models");
# publications
Meteor.publish("Brands", function(){
return Brands.find();
});
Meteor.publish("Models", function(){
return Models.find();
});
# fixtures
if (Brands.find().fetch().length === 0){
var brands = ["Audi", "BMW", "Chrysler"];
var models = {
"Audi": ["A3", "A4", "A5"],
"BMW": ["3 Series", "4 series", "5 series"],
"Chrysler": ["200", "300"]
};
for (var i = 0; i < brands.length; i++){
Brands.insert({name: brands[i]});
for (var j = 0; j < models[brands[i]].length; j++){
Models.insert({name: models[brands[i]][j], brand: brands[i]})
}
}
}