dedi wibisono dedi wibisono - 17 days ago 5
jQuery Question

How using 'for each' in select option?

I want to ask about for each
here's my HTML

<select class="namaKota" id="fromCity"></select>


my data in js

var listCity =
{
"Popular":
[
{"cityname":"London","code":"LDN"},
{"cityname":"Rome","code":"ROM"},
{"cityname":"Madrid","code":"MDR"}
],
"Germany":
[
{"cityname":"Hamburg", "code":"HMB"},
{"cityname":"Frankfurt", "code":"FRN"}
]
}


and here's my JS

var a = $("select#fromCity").val();
listKota.forEach(function(e){
a.append('<option value="'+ listCity.code +'">'+ listCity.cityname +'</option>');});


I want be like this image. How can I create using for each?

enter image description here

Here's my jsfiddle. https://jsfiddle.net/dedi_wibisono17/9u9uec8d/1/ Anybody help? Thankyou

Answer

The layout you have in your image uses <optgroup> elements to group the <option>. Therefore you need two loops; one to create the optgroups from the keys of the object, and another to populate the actual option within those groups. Try this:

var listCity = {
  "Popular": [
    { "cityname": "London", "code": "LDN" },
    { "cityname": "Rome", "code": "ROM" },
    { "cityname": "Madrid", "code": "MDR" }
  ],
  "Germany": [
    { "cityname": "Hamburg", "code": "HMB" },
    { "cityname": "Frankfurt", "code": "FRN" }
  ]
}

Object.keys(listCity).forEach(function(key) {
  var $group = $('<optgroup label="' + key + '"></optgroup>');

  listCity[key].forEach(function(obj) {
    $group.append('<option value="' + obj.code + '">' + obj.cityname + '</option>')
  })

  $('#fromCity').append($group);
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select name="" id="fromCity"></select>

Comments