最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - create drop down list from json - Stack Overflow

programmeradmin1浏览0评论

I have a json in this form:

{"COLUMNS":["ID", "Name"],"DATA":
[ 
  ["1","Joe"],
  ["2", "Sam"],
  ["3", "Doug"],
]
}

and I was looking for an example of how to create a drop down list from this data in javascript but all the examples of json/dropdown list the json is in a different format. I haven't worked with javascript much or json data at all so I'm not sure about where to start. Can anyone point me in the direction of a great tutorial or examples? Thanks.

I have a json in this form:

{"COLUMNS":["ID", "Name"],"DATA":
[ 
  ["1","Joe"],
  ["2", "Sam"],
  ["3", "Doug"],
]
}

and I was looking for an example of how to create a drop down list from this data in javascript but all the examples of json/dropdown list the json is in a different format. I haven't worked with javascript much or json data at all so I'm not sure about where to start. Can anyone point me in the direction of a great tutorial or examples? Thanks.

Share Improve this question asked Jul 15, 2013 at 5:03 user2533762user2533762 691 gold badge2 silver badges14 bronze badges 1
  • can u please explain how you are getting this json response? – Aarif Qureshi Commented Jul 15, 2013 at 5:08
Add a ment  | 

2 Answers 2

Reset to default 2

The JavaScript:

window.onload = function () {
    var JSON = {
        "COLUMNS":["ID", "Name"],
        "DATA": [ 
            ["1","Joe"],
            ["2", "Sam"],
            ["3", "Doug"]
        ]
    }, select = document.getElementById("selector");
    for (var i = 0, at = JSON.DATA[i], id = at[0], name = at[1]; i < JSON.DATA.length; i++) {
        var option = document.createElement("option");
        option.value = id;
        option.textContent = name;
        select.appendChild(option);
    };
};

Please make sure that if your JSON is in string form, that you parse it first using JSON.parse();

The HTML:

<select id="selector"></select>

The JSFiddle Example: http://jsfiddle/su7sr/1

I thing that correct JS will be:

window.onload = function () {
    var JSON = {
        "COLUMNS":["ID", "Name"],
        "DATA": [ 
            ["1","Joe"],
            ["2", "Sam"],
            ["3", "Doug"]
        ]
    }, select = document.getElementById("selector");
    for (var i = 0; i < JSON.DATA.length; i++) {
    var at = JSON.DATA[i], id = at[0], name = at[1];
        var option = document.createElement("option");
        option.value = id;
        option.textContent = name;
        select.appendChild(option);
    };
};
发布评论

评论列表(0)

  1. 暂无评论