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);
0

2 Answers 2

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>

Sign up to request clarification or add additional context in comments.

Comments

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>

7 Comments

Just the worse way I've ever seen to loop through an array!
@ibrahimmahrir Have you seen better implementation in pure JS, working also on IE<=8?
What about for(var i = 0; i < serverTypes.length; i++) { ... }??? Are you familiar with it???
It's much better. Anyway, there is no need for rage here, so calm down please.
There is no rage! I just gave you a hint that's all!
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.