Jquery 3.3.1从JSON对象填充Dropdown

时间:2018-03-30 13:13:11

标签: jquery-3

尝试运行一个简单的示例来将JSON对象解析为下拉列表。使用最新的jquery-3.3.1.js和IE 11. Coud有人纠正下面的样本吗?

var test = { Cars: [{"CarType": "BMW","carID": "bmw123"},{"CarType": "mercedes","carID": "merc123"}, {"CarType": "volvo","carID": "vol123r"}, {"CarType": "ford", "carID": "ford123"}]};

$(document).ready(function(){           
  var mySelect = $('#reportingQuarter');
    $.each(test.Cars, function(key, value) {   
    mySelect.html($("<option></option>").attr("value",key).text(value)); 
    }); 
 })

<div class="col-md-4 mb-3">
 <label for="reportingQuarter">Reporting Quarter</label>
 <select class="form-control" id="reportingQuarter" required>
 <option value="">Please choose Report Quarter</option>
 </select>
   <div class="invalid-feedback">
   Please select Reporting Quarter.
   </div>
 </div>

错误:      下拉列表仅显示[object Object]

2 个答案:

答案 0 :(得分:-1)

试试这个

$.each(test.Cars,function(key, value) {
  $("#mySelect").append($('<option></option>').val(value.carID).html(value.CarType));
});

答案 1 :(得分:-1)

我不想带走你的编码风格,但要认真试试。

 <!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
var test = { Cars: [{"CarType": "BMW","carID": "bmw123"},{"CarType": "mercedes","carID": "merc123"}, {"CarType": "volvo","carID": "vol123r"}, {"CarType": "ford", "carID": "ford123"}]};

$(document).ready(function(){           
  var mySelect = $('#reportingQuarter');
    $.each(test.Cars, function(key, value) {   
    $("#reportingQuarter").append("<option value="+value.CarType+">"+value.CarType+"</option>"); 
    }); 
 })
</script>
<div class="col-md-4 mb-3">
 <label for="reportingQuarter">Reporting Quarter</label>
 <select class="form-control" id="reportingQuarter" required>
 <option value="">Please choose Report Quarter</option>
 </select>
   <div class="invalid-feedback">
   Please select Reporting Quarter.
   </div>
 </div>