0

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.

0

2 Answers 2

3

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

Sign up to request clarification or add additional context in comments.

Comments

0

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);        
    });



});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.