Search code examples
javascriptmeteormeteor-helper

Filter collection based on select dropdown box in meteor


I am trying to filter my collection based on the selection of value from select dropdown list. I have tried with the solutions here and here and its not working enough for me. Below is the template where i want to filter.the select dropdown is in another template categoryFilter which iam calling here using {{> categoryFilter}} to filter the list of collections under {{#each car}} block. The field i am using in schema is ccategory which i want to filter

<template name="carsList">
  <div class="col s12 filter-holder">
        <div class="col m4 s4 filter-box">
          {{> categoryFilter}}
        </div>
 </div>

<div class="col s12">
 <ul class="collection" id="listings">
{{#each cars}}
<li>
  {{> carItem}}
</li>
{{/each}}
</ul>
</div>
</template>

this is my existing helper for calling all cars

Template.carsList.helpers ({
'allCars': function() {
  return Cars.find();
},
});

this is how my event look like for this. var pageSession=ReactiveDict();

 Template.carsList.events({
  "click .categoryselection": function(e, t){
 var text = $(e.target).text();
  pageSession.set("selectedCategory",text);
 }
 });

I am using ReactiveDict() package for this filtering.Am i doing it right till now? How can i filter the values and call them on the <ul> list and filter <li> values.Please help me


Solution

  • Since you are only storing one value at a time (the selected category), there is no real need to use a ReactiveDict for this case, is there? If so, you could do it with a ReactiveVar instead:

     Template.carsList.onCreated(function () {
       this.selectedCategory = new ReactiveVar();
     });
    
    Template.carsList.helpers ({
    'allJobs': function() {
      var category = Template.instance().selectedCategory.get();
      return Cars.find(category ? {ccategory: category} : {});
    },
    });
    
     Template.carsList.events({
      "click .categoryselection": function(e, t){
     var text = $(e.target).text();
      t.selectedCategory.set(text);
     }
     });
    

    If you still want to use a ReactiveDict for multiple filter values such as ccategory and city, you could go with:

    Template.carsList.helpers ({
    'allJobs': function() {
      var filter = {};
      var category = pageSession.get("selectedCategory");
      var city = pageSession.get("selectedCity");
      if (city)
        filter.city = city;
      if (category)
        filter.ccategory = category;
      return Cars.find(filter);
    },
    });
    
     Template.carsList.events({
      "click .categoryselection": function(e, t){
     var text = $(e.target).text();
      pageSession.set("selectedCategory",text);
     },
      "click .cityselection": function(e, t){
     var text = $(e.target).text();
      pageSession.set("selectedCity",text);
     }
     });