hagay bar hagay bar - 3 months ago 14
JSON Question

Trying to extract output from a json file based on user selection in a drop-down-menu

I am trying to present a user with a drop-down-list and give an output based on user's selection. The drop-down-list options are populated via a json file and I want the output to come from the json (based on the selection of course).

This is the json:

{
"101": {"title":"a title",
"shelf":"shelf 1",
"floor":"1",
"udcStartAt":"123.3",
"udcEndAt":"133.29"},
"102": {"title":"b title",
"shelf":"shelf 2",
"floor":"1",
"udcStartAt":"133.3",
"udcEndAt":"134.69"},
"103": {"title":"c title",
"shelf":"shelf 3",
"floor":"1",
"udcStartAt":"134.7",
"udcEndAt":"136.59"}
}


This is my current javascript:

//this one gets the json and sends it to the jsonToDdl(data) function

function simpleJsonShow(){
$.getJSON("test.json", jsonToDdl);
}

//this one populate the drop-down-list

function jsonToDdl(data){
for (sNumber in data){
$("#selectNumberTwo").append("<option>" + sNumber + "</\option>");
}
}


I want the output to be the nested values for each option, for example - when 101 is selected, the output should be: 1 , 123.3 , 133.29.

I have looked for solution here but I did not fully understand the method presented there.

Answer

I got it

function showNestedOutput(){
$.getJSON("data\\topicToShelf.json", showNestedResult);  /*get json file and pass to showNestedResult()*/
function showNestedResult(data){
    var selection = $("#selectTopic option:selected").text(); // the var 'selection' stores user's selection text
    var nestedResult = "your result" + data[selection].title + " located: " + data[selection].shelf + " floor: " + data[selection].floor;
    $("#outputTopics").html(nestedResult);
    }

}
Comments