0

I have a select element and I want to add select options from javascript. I have a ajax method and this method returns JSON object like;

"{"serverTypes":["WINDOWS","LINUX"]}"

I want to add options from this JSON. Is there any way to do this?

<select id="serverTypes" name="serverType" class="form-control"></select>

EDIT:
Setting value is not working

$('#serverTypes').val(jsonData);
hellzone
  • 5,393
  • 25
  • 82
  • 148

2 Answers2

5

You can loop through the JSON and append() the values:

var json = {
  "serverTypes": ["WINDOWS", "LINUX"]
};
for (var x = 0; x < json.serverTypes.length; x++ ) {
  var option = json.serverTypes[x];
  $('#serverTypes').append('<option value="' + option + '">' + option + '</option>')
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="serverTypes" name="serverType" class="form-control"></select>
Ionut Necula
  • 11,107
  • 4
  • 45
  • 69
2

var data = {"serverTypes":["WINDOWS","LINUX"]};
var serverTypes = data.serverTypes;

var option;
for (var i in serverTypes) {
    if (serverTypes.hasOwnProperty(i) && i!="length"){
        option = $('<option></option>');
        option.val(serverTypes[i]);
        option.text(serverTypes[i]);

        $("#serverTypes").append(option);
    }
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="serverTypes" name="serverType" class="form-control"></select>
michail_w
  • 4,318
  • 4
  • 26
  • 43