Create a JSON string from a JavaScript array.
FULL CODE BELOW
<!DOCTYPE html>
<html>
<body>
<h2>Create a JSON string from a JavaScript array.</h2>
<p id="demo"></p>
<div id="select_box_wrapper">
<select id="countries" onchange="show(this)"></select>
</div>
<p id="msg"></p>
<div class="row">
<div class="col">
<input type="text" id="lat" placeholder="45.48" value="" required autofocus>
</div>
<div class="col">
<input type="text" id="lon" placeholder="15.58" value="" required autofocus>
</div>
</div>
<script>
LET (MAKE IT FROM API)
const arr = {"geonames":[{"place_name":"Delhi","latitude":"28.65381","longitude":"77.22897","timezone_id":"Asia/Kolkata","country_code":"IN"},{"place_name":"Delhi112","latitude":"37.43216","longitude":"-120.7785","timezone_id":"America/Los_Angeles","country_code":"US"},{"place_name":"Delhi Hills","latitude":"39.09284","longitude":"-84.61272","timezone_id":"America/New_York","country_code":"US"}]};
var selectHTML='';
for (i=0; i < arr.geonames.length; i++) {
selectHTML +='<option value="'+arr.geonames[i].latitude+','+arr.geonames[i].longitude+'">'+arr.geonames[i].place_name+'-'+arr.geonames[i].timezone_id+'</option>';
}
document.getElementById('countries').innerHTML = selectHTML;
function show(ele) {
// GET THE SELECTED VALUE FROM <select> ELEMENT AND SHOW IT.
let msg = document.getElementById('msg');
msg.innerHTML = 'Selected City: <b>' + ele.options[ele.selectedIndex].text + '</b> </br>' +
'City: <b>' + ele.value + '</b>';
const myArray = ele.value.split(",");
document.getElementById('lat').value=myArray[0];
document.getElementById('lon').innerHTML=myArray[1];
}
</script>
</body>
</html>
Post a Comment
0Comments