dedi wibisono dedi wibisono - 8 months ago 45
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 =
{"cityname":"Hamburg", "code":"HMB"},
{"cityname":"Frankfurt", "code":"FRN"}

and here's my JS

var a = $("select#fromCity").val();
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. Anybody help? Thankyou


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>')

<script src=""></script>
<select name="" id="fromCity"></select>