dedi wibisono dedi wibisono - 1 year ago 82
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

Answer Source

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>

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download