Question

I can have any JSON returned from a service. Based on the JSON, I need to dynamically create SelectBoxes and fill in the values in them.

Eg-

 JSON = {
    "Level": [{
        "Product": [{
            "ID": "ID1",
                "Brand": "Brand2",
                "Type": "Type3",
                "Line": "Line4",
                "Family": "Family5"
        }],
            "Location": [{
            "City": "City1",
                "State": "State2",
                "Region": "Region3",
                "Country": "Country4"
        }],
            "Time": [{
            "Day": "Day1",
                "Week": "Week2",
                "Month": "Month3",
                "Quarter": "Quarter4",
                "Year": "Year5"
        }]

    }]
} 

In this case, 3 main select boxes will be created with subselect boxes under them. Like - OneMain SelectBox - Time, Under time 5 more select boxes, Second SelectBox - Location, Under that 4 more select boxes and so on.

Am completely clueless how to make it dynamic to such level.

Was it helpful?

Solution

Try this,

var level=JSON['Level'][0];
for(var pr in level){
    var $select =$('<select/>');
    $select.append('<option>'+pr+'</option>');
    key=level[pr][0];
    for(k in key){
         $select.append('<option>'+key[k]+'</option>'); 
    }
    $select.appendTo('body');
}

Live Demo

OTHER TIPS

hi i think this is what you want example, iam using Jquery

var  JSONS = {
    "Level": [{
      "Product": [{
            "ID": "ID1",
                "Brand": "Brand2",
                "Type": "Type3",
                "Line": "Line4",
                "Family": "Family5"
        }],
            "Location": [{
            "City": "City1",
                "State": "State2",
                "Region": "Region3",
                "Country": "Country4"
        }],
            "Time": [{
            "Day": "Day1",
                "Week": "Week2",
                "Month": "Month3",
                "Quarter": "Quarter4",
                "Year": "Year5"
        }]

    }]
} 

$(document).ready(function(){
    $.each(JSONS.Level[0],function(key,val){
       var currentSection = val[0];

        var selectEle=$('<select id="'+key+'"></select>');
        $.each(currentSection,function(k,va){
          var op =  "<option>"+va+"</option>";
            selectEle.append(op);

        });

        $('#selectWrap').append(selectEle);        
    });



});
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top