I have a JSON data whose values should be fetched using Javascript variables.
Here's the HTML
<body>
<form action="#" action="get">
<select name="college" id="college" onchange="selection('college', 'course')">
<option value="base">base</option>
<option value="amity">Amity University</option>
<option value="indraprastha">Indraprasth University</option>
</select>
<br>
<select name="course" id="course" >
<option value="base">Base</option>
</select>
<br>
<select name="stream" id="stream"></select>
<br>
<select name="sem" id="sem"></select>
<br>
<select name="subject" id="subject"></select>
</form>
</body>
Here's the JSON
{
"amity": [
{
"name": "B.Tech,btech"
},
{
"name": "M.tech,mtech"
}
],
"indraprastha": [
{
"name": "B.Tech,btech"
},
{
"name": "Mtech,mtech"
}
]
}
and here's the JS
function selection(s1, s2) {
var first = document.getElementById(s1),
second = document.getElementById(s2);
$.getJSON("json/list.json", function(data) {
var college = $('#college').val();
$.each(data[college][0], function(key, value) {
alert(value);
});
});
}
Now the problem is, using the first drop-down for college, I can get the value of college using .val() function. But for second drop-down which is dynamic, I want the values inside the college data array of JSON, but for some reason I am not able to access it unless appending an array index [0], the reason for which I know, since it's array. But the value should come from course drop-down which is currently empty.
I want all the values inside the amity data array to go into second drop-down. Then from that I can access it like, data[college][course]
Are there any solutions for accessing the complete amity array and get all it's objects. Also, can you suggest article on creating at least 3-4 level dynamic drop-down menu.
Thanks in advance.
[0]. The .each call will take care of iterating over the array, sokeywill actually be the index, and value will be the corresponding value. Since you have an array of objects,valuewill be a reference to an object, so you'll need to reference the name property:value.name. If you want to populate items in a select, though, I'd suggest you split out the value and the display text, rather than having them joined in what looks like a comma-separated string (i.e. change your JSON structure a bit).