dedi wibisono dedi wibisono - 19 days ago 5
Javascript Question

Select default array from for each in option value

I want to set default selected from 'Rome'

here is my 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" }
]
}

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

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


I try this, but still bug. Anybody help or suggestion?
Here's my jsfiddle: https://jsfiddle.net/dedi_wibisono17/0c1js6wa/1/

Thank you

Answer

you can set the value just after appending the optgroup html in the select element.

 $('#fromCity').append($group);

  $('#fromCity').val("ROM");

Fiddle : https://jsfiddle.net/5gpbvhff/