6

I have a simple JSON code:

[{'1':'Name'}, {'2', 'Age'}, {'3','Gender'}]

I have a select tag in my HTML:

<select name="datas" id="datas"></select>

I need a simple way to create HTML select box from this JSON, like this:

<select name="datas" id="datas">
    <option value="1">Name</option>
    <option value="2">Age</option>
    <option value="3">Gender</option>
</select>
1
  • Some tips: foreach(), document.createElement(), and .appendChild(). Commented Jan 30, 2012 at 22:10

3 Answers 3

11

Just for kicks here is an answer in pure javascript, also you probably do not need an array for this just a simple object will suffice

    <select name="datas" id="datas"></select>
    <script>

        html = "";
        obj = {
            "1" : "Name",
            "2": "Age",
            "3" : "Gender"
        }
        for(var key in obj) {
            html += "<option value=" + key  + ">" +obj[key] + "</option>"
        }
        document.getElementById("datas").innerHTML = html;

    </script>
Sign up to request clarification or add additional context in comments.

1 Comment

key and obj[key] should at least be properly encoded. Imagine if obj = {"1" : "> one &","2":"This has a quote \" in it"}. It is safer to generate it using .append than joining html strings
8

Try this.

//Correct(missing colons) in the array items
var data = [{'1':'Name'}, {'2': 'Age'}, {'3': 'Gender'}];

Create option element and then use append method to append them into select element.

var $select = $('#datas');
$.each(data, function(i, val){
    $select.append($('<option />', { value: (i+1), text: val[i+1] }));
});

Demo

Comments

1

The above answer assumes that the data indexes of the array are in order. What if the data variable would be:

var data = [ {'23':'Age'}, {'12':'Gender'}, {'3':'Name'}];

So in alphabetical order, but with random id's.

One way I found in solving this is:

$.each(data, function(key, value) {
  var i = Object.keys(value)[0];
  $("select#datas").append( $("<option />").val(i).text(value[i]) );

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.