Reputation: 195
i need to create drop down list based on following json array,there will be 5 drop down list , if i select i need to populate other four for example if i select Hindi in first drop-down list then
Second list Third list Forth list Fifth list
"History", "Philosophy", "Political Science" "English"
"Sociology", "BLANK" "BLANK" "BLANK"
"Economics"
Now when i use jquery to implement this the list is not populating properly.I can not break down the inner array. i am attaching link of jsfidle.Do i have to change the json format.
{
"Hindi": [
[
"History",
"Sociology",
"Economics"
],
"Philosophy",
"Political Science",
"English"
],
"Bengali": [
["History" ,"Sociology"
],
"Sanskrit",
"Philosophy",
"Political Science"
],
"English": [["History","Sociology","Economics"],
"Philosophy",
"Political Science",
["Bengali","Hindi"]
]
}
Upvotes: 0
Views: 1979
Reputation: 1785
When parsing JSON assume that you have the same structure for every dropdown :
{"1select":[["2select values..."],[3select values..."],[4select values..."],[5select values..."]]}
(if there is no array
-> create one)
and than do the same for every dropdown.
CODE :
var jsonObj = {"Hindi":[["History","Sociology","Economics"],"Philosophy","Political Science","English"],"Bengali":[["History","Sociology"],"Sanskrit","Philosophy","Political Science"],"English":[["History","Sociology","Economics"],"Philosophy","Political Science",["Bengali","Hindi"]]}
function updateSelect() {
var getOpts = function(raw){
var values = raw;
if (!(raw instanceof Array)){
values = [raw, ""];
}
var result = [];
values.forEach(function(obj){
result.push(new Option(obj, obj));
});
return result;
};
var newKey = $("#select1").val();
var mappings = [{"#select2":0},{"#select3":1},{"#select4":2},{"#select5":3}];
var selected = jsonObj[newKey];
mappings.forEach(function(mapping){
var selector = Object.keys(mapping)[0];
var index = mapping[selector];
$(selector).empty();
var opts = getOpts(selected[index]);
$(selector).append(opts);
});
}
$(document).ready(function() {
$("#select1").change(updateSelect);
updateSelect(); // For initial page load.
});
Example : here
Upvotes: 1