Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / Languages / Javascript

How To Populate a Select Element with Data From a JSON File in a Meteor App

5.00/5 (1 vote)
3 Sep 2015CPOL1 min read 11.7K  
Populating Select Elements' Options Values with lookup data stored in your settings.json file in your Meteor apps

The No-No SQL Way of populating Select Elements' Options Values

In a previous tip here, I showed how you can insert values into a MongoDB ("No SQL") Collection and then read them out using Meteor's Spacebars template language to populate a Select elements' Options values. This tip is similar but, instead of storing the data in and retrieving it out of a MongoDB Collection, it is stored/retrieved from a .json file. Here are the steps to do that:

First, put some data into a file, perhaps named settings.json, that resides directly beneath your project folder:

JavaScript
{"public" : { "uccampus": [ {"name":"UC Santa Cruz"}, {"name":"UC Berkeley"}, 
{"name":"UC Davis"}, {"name":"UC Irvine"}, {"name":"UC Los Angeles"}, 
{"name":"UC Merced"}, {"name":"UC Riverside"}, {"name":"UC San Diego"}, 
{"name":"UC San Francisco"}, {"name":"UC Santa Barbara"} ] }}
}

Second, add a helper for the Template in which the Select element resides, like so:

JavaScript
Template.tblTravelerInfo2.helpers({
    uccampus: function(){
        return Meteor.settings.public.uccampus;
    }
});

Third, add this to the HTML for that Select element (instead of things like "<option value="dp">Duckbilled Platypus</option>"):

JavaScript
{{#each uccampus}}
  <option>{{name}}</option>
{{/each}}

Note: When using this code, and running your Meteor app from its directory in the console, it is not enough to simply enter "meteor run" or "meteor". You need to enter "meteor --settings settings.json" (where "settings.json" is the name of the file containing the json data); and the said json file must reside directly beneath your project's folder - not in a subfolder.

Don't Neglect the Superhero's Superhero (After Meteor Man, of course)

If you like this tip, tip your hat to Top Cat the next time that you see him. If you have no hat, tip your toupée; if you don't wear a toupée, tou·ché Turtle soup of the day Trip the Light Fantastic Four Horsemen of the Apocalypse sinks ships ahoy, Matey s. Eliott Gould.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)