Search code examples
javascriptjqueryjsonjquery-selectbox

Creating dynamic SelectBoxs based on JSON using jquery


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.


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