Populating select box with JSON tutorial example
JSON [JavaScriptObjectNotation] has become the defacto standard for web-consumers these days.
I also interact with it in a frequent manner.
The major usage might be when you are interacting with API based websites. Even though there are multiple response types, json is one of the most widely endorsed these days.
Based on the response you can apply it to different parts of the web app.
When would I be using json for select boxes?
Lets say you are calling an API to give you the list of available cars and the API would return the result in json format.
Then you can use that response as a selection in select box or you can also list it as options to be checked in the form of checkboxes and the like.
Node tutorial with http web server
Here is example of using json response used in select box
I will try to give some simple example on using JSON with old school javascript and jquery.
Lets have the following JSON for our example:
var cars=[{"color":"red","made":"toyota","model":"corrola","mileage":"10000"},{"color":"silver","made":"honda","model":"accord","mileage":"160000"},{"color":"white","made":"nissan","model":"maxima","mileage":"12200"}];
Just ordinary simple data to play with.
Using Old School Javascript:
Assuming there is select box with id “dynamic_slct”
var options = '';
slctbox = document.getElementById('dynamic_slct');
for(var i=0 ; i<cars.length ; i++)
{
var label = cars[i]['made'];
var model = cars[i]['model']; //or whatever the value you want to show
var opt = document.createElement('option');
slctbox.options.add(new Option(label, model));
}
As simple as that, the ‘cars’ should be available on the page being accessible to the javascript that is populating the options. If you are working on PHP, for example, spitting the json_encode(array) would provide what is needed for this
Uisng jQuery
var opt="";
$.each(cars, function(){
var label = this['made'];
var model = this['model'];
opt += ""+model+"";
});
$('#dynamic_slct').html(opt);