jquery-3

Jquery 3.3.1 populate Dropdown from JSON object


Trying to run a smaple example to parse a JSON object to the dropdown. Using latest jquery-3.3.1.js and IE 11. Coud some one correct the below sample ?

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>

Error: Dropdown showing only [object Object]


Solution

  • Try this

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