我有一个select元素,我想从javascript中添加select选项。我有一个ajax方法,这个方法返回JSON对象,如;
"{"serverTypes":["WINDOWS","LINUX"]}"
我想从这个JSON中添加选项。有没有办法做到这一点?
<select id="serverTypes" name="serverType" class="form-control"></select>
修改
设定值无效
$('#serverTypes').val(jsonData);
答案 0 :(得分:5)
您可以遍历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>')
}
和append()值:
<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>
&#13;
{{1}}&#13;
答案 1 :(得分: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);
}
}
&#13;
<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>
&#13;