How to create HTML select option from JSON hash?

后端 未结 3 930
孤独总比滥情好
孤独总比滥情好 2020-12-09 07:13

I have a simple JSON code:

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

I have a select tag in my HTML:



        
相关标签:
3条回答
  • 2020-12-09 07:35

    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>
    
    0 讨论(0)
  • 2020-12-09 07:35

    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

    0 讨论(0)
  • 2020-12-09 07:44

    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]) );
    
    0 讨论(0)
提交回复
热议问题