AGS
AGS

Reputation: 427

execute code after selection from dropdown

I am building a meteor based webapp. One of the pages has a drop down menu, which the user has to select options (various school districts) from. The selection needs to be detected, followed by querying the database filtering documents based on the selection and counting the documents returned, followed by rendering a template (a chart built using highcharts.js)

Code as follows:

Template.districtDropdown.events({
  'change' : function(event, template){
    event.preventDefault();
    var selectedValue = template.$("#selectDistrict").val();
    console.log("You Selected " + selectedValue);
    var filter = {
      find: {
        'School District' : selectedValue
      }
    };
    Meteor.subscribe('aggByDistrict', filter);
    productNames2 = _.uniq(CombinedData.find().map( function(doc) { return doc.Product; }));
    console.log(productNames2);
    var productValues2 = [];
    for(var i = 0; i < productNames2.length; i++) {
      productValues2.push(CombinedData.find({'Product' : productNames2[i]}).count())
    };
      console.log(productValues2);
  }
});

I'm facing three issues.

  1. The console on the client side throws an error "productNames2" has not been defined as soon as the page loads, pointing to the line which has the for loop (even before I've made any selection).
  2. The first time I click on one of the options in the drop down menu, I get empty arrays (the two console.log(productNames2) and console.log(productValues2), but when I click on some other option, it works the second time. No idea why.
  3. I want to render a template {{> highchart2}} after the user has selected an option from the drop down and the two arrays (productNames2, productValues2) have been populated.

Can anyone give me ideas on how I can go about resolving these issues?

Upvotes: 1

Views: 108

Answers (1)

Thai Tran
Thai Tran

Reputation: 9935

Several problems with your code

  1. Subscribe needs to be put in Template.districtDropdown.created. If you subscribe during the events, there might be the postpone during the subscription and no data available during the events
  2. event should be attached to a DOM component. As in change #selectDistrict and then, you select the value like this var selectedValue = $(event.target).val();

Upvotes: 1

Related Questions