-2

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]

Graciano
  • 508
  • 4
  • 11
user3067524
  • 506
  • 4
  • 10
  • 26
  • JSON is spelt without an A, and [that isn't JSON](http://benalman.com/news/2010/03/theres-no-such-thing-as-a-json/). – Quentin Mar 30 '18 at 13:24

2 Answers2

-1

Try this

$.each(test.Cars,function(key, value) {
  $("#mySelect").append($('<option></option>').val(value.carID).html(value.CarType));
});
Graciano
  • 508
  • 4
  • 11
-1

I don't wanna take away your coding style but seriously try this.

 <!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>
Rishabh Kandari
  • 150
  • 4
  • 16