Search code examples
getjson

Iterate json data in select option


I am using $.getJSON and it is return below json data.

{
    "sEcho": 1,
    "iTotalRecords": 2,
    "iTotalDisplayRecords": 2,
    "aaData": [
        {
            "student": {
                "id": "1",
                "name": "gaurav"
            }
        },
        {
            "student": {
                "id": "2",
                "name": "abhishek"
            }
        }
    ]
}

I want to put student id and name into the select option value. Html will be like this :

<select name='stud'>
<option id='1'>gaurav</option>
<option id='1'>abhishek</option>
</select>

When am use JSON.stringify it is returning object object. Thanks in advance.


Solution

  • Is this what you are after ? (assumes that you are using jQuery on your page):

    <script type="text/javascript">
    var json = {
        "sEcho": 1,
        "iTotalRecords": 2,
        "iTotalDisplayRecords": 2,
        "aaData": [
            {
                "student": {
                    "id": "1",
                    "name": "gaurav"
                }
            }, {
                "student": {
                    "id": "2",
                    "name": "abhishek"
                }
            }
        ]
    };
    
    json.aaData.forEach(function(value) {   
        var student = value.student
         $('#mySelect')
             .append($("<option></option>")
             .attr("value",student.id)
             .text(student.name)); 
    });
    </script>
    
    <select id='mySelect' name='stud'>
    </select>
    

    See working example on here: http://jsfiddle.net/r5nn5wqu/