简体   繁体   中英

Cannot fetch data from json using select in javascript

I am new in Json and javascript . What I want is a select tag with option, thus by selecting the options - that particular object will be fetched from JSON and will be displayed , I have used Nested JSON .

data.json:

var data = {

        "abc":{
            "color":["rgb(4,45,97)","rgb(255,122,0)"],
            "font":"Interface Thin",
            "logo":"<img src='logo.png' width='200' height='150'>"
        }


    }

index.html

<!doctype html>
<html>
<head>
<meta charset="utf-8">
<script type="text/javascript" src="data.json"></script>
</head>

<body>
<!--document.getElementById('color').innerHTML += '<div style="border:1px solid black;padding:2px;width:100px;background-color:'+data.AllenandHanburys[j]+';height:100px"></div>'-->

<p id="demo"></p>
<p id="color"></p>
<p id="logo"></p>

<select id="brand" onChange="run()"> 
    <option>Select Option</option>
    <option value="abc">abc</option>
</select>
</body>

<script>
var i;
function run() {
var brand_name=document.getElementById('brand').value;//
for(x in data)
{
    if(x==brand_name)
    {
        for(j in data.brand_name)
            {
                document.getElementById('demo').innerHTML +=j+":"+data.abc[j]+"<br>";
                if(j=='color')
                    {
                            for(i=0;i<data.abc.color.length;i++)
                            {
                                document.getElementById('color').innerHTML +='<div style="border:1px solid black;padding:2px;width:100px;background-color:'+data.abc.color[i]+';height:100px"></div>'+"<br>";
                            }


                    }



            }
    }
}
}
</script>

</html>

this line is wrong,

for(j in data.brand_name) //because `brand_name` property is not exist in the object

change it to

for(j in data[brand_name]) //data[brand_name] will parsed as data['abc'] which is same as data.abc

Here's the demo

 var data = { "abc":{ "color":["rgb(4,45,97)","rgb(255,122,0)"], "font":"Interface Thin", "logo":"<img src='logo.png' width='200' height='150'>" } } var i; function run() { var brand_name=document.getElementById('brand').value;// for(x in data) { if(x==brand_name) { for(j in data[brand_name]) { document.getElementById('demo').innerHTML +=j+":"+data.abc[j]+"<br>"; if(j=='color') { for(i=0;i<data.abc.color.length;i++) { document.getElementById('color').innerHTML +='<div style="border:1px solid black;padding:2px;width:100px;background-color:'+data.abc.color[i]+';height:100px"></div>'+"<br>"; } } } } } }
 <p id="demo"></p> <p id="color"></p> <p id="logo"></p> <select id="brand" onChange="run()"> <option>Select Option</option> <option value="abc">abc</option> </select>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM