Category Archives: Javascript

Read JSON using JavaScript

Hi Guys,

Here we are going to have a simple code which will show how to read data from JSON and fill Dropdown. All will be done through JavaScript.

Very first thing we are going to make one JSON object with Weather Information city wise.

After that we have made some functions which will be used to fill the dropdown list for City and Weather.

<script language="javascript" type="text/javascript">

var objJSON = { "weatherdetails":
    {
        "weatherreport":
            [
                {"city": "Mumbai", "weather": "32" },
                {"city": "Delhi", "weather": "28" },
                {"city": "Chennai", "weather": "34" },
                {"city": "Kolkata", "weather": "26" }
            ]
    }
};

var obj = eval(objJSON.weatherdetails);

function showJSON(){
    for(var i=0;i<obj.weatherreport.length;i++){
    alert(obj.weatherreport[i].city + "----" + obj.weatherreport[i].weather);
    }
}

function LoadCity(){
    var optionCity = "Select One City";
    document.getElementById("ddlCity").options[0] = new Option(optionCity, "0");
    for(var i=0;i<obj.weatherreport.length;i++){
        document.getElementById("ddlCity").options[i+1] = new Option(obj.weatherreport[i].city, obj.weatherreport[i].city);
    }

}

function LoadWeather(){

    var optionWeather = "Select One Weather";
    document.getElementById("ddlWeather").options[0] = new Option(optionWeather, "0");
    for(var i=0;i<obj.weatherreport.length;i++){
        document.getElementById("ddlWeather").options[i+1] = new Option(obj.weatherreport[i].weather, obj.weatherreport[i].city);
    }
}

function showWeather(ctrl){
    var strCity = ctrl.options[ctrl.selectedIndex].value;
    var strWeather = document.getElementById("ddlWeather");
    for(var i = 0; i < strWeather.length; i++)
       {
        if(strWeather.options[i].value == strCity){
                  strWeather.selectedIndex = i;
            return;
        }

       }
}

</script>

 

Below is the HTML code:

<div>
       <input type="button" id="btnShow" value="Show City and Weather" onclick="showJSON();" /></div>
<div>
       <input type="button" id="btnLoadCity" value="Load City" onclick="LoadCity();" />
       <select id="ddlCity" onChange="showWeather(this);"></select>
<div id="dvCity"></div>
</div>
<div>
        <input type="button" id="btnLoadWeather" value="Load Weather" onclick="LoadWeather();" />
        <select id="ddlWeather"></select>
</div>

 

Below is the code which used to load the dropdown list on onload function.

<script language="javascript" type="text/javascript">
function loadData(){
    LoadCity();LoadWeather();
}

window.onload = loadData;
</script>

 

This is final output of above code :

JSON

Advertisements