I'm currently working on a web form for a currency exchange demonstration. I have included a snippet of HTML and Javascript code that I have initially implemented.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>Currency Exchange</title>
<link rel="stylesheet" type="text/css" href="styles/styles.css" />
</head>
<body>
<h1>Currency Exchange Rates to US Dollar</h1>
<select id="currencies" onchange="getCurrency()">
<option value="">Select a Currency</option>
<option>UK Pounds</option>
<option>Euros</option>
<option>Yen</option>
<option>Yuan</option>
<option>Swiss Francs</option>
<option>Canadian Dollars</option>
</select>
<p id="exchangerate"></p>
</body>
</html>
Apologies for the beginner question. I'm attempting to store currency data in a JavaScript object and display it in a dropdown menu. How can I retrieve the values from the object to populate the dropdown menu?
I've tried storing the data in an object, but it doesn't seem to be working as intended. I'm also unsure if using single quotes for a variable is the correct approach - it's the only method that has worked for me so far.
let rates = {
UKPounds: 0.75,
Euros: 0.9,
Yen: 109.44,
Yuan: 7.02,
SwissFrancs: 0.98,
CanadianDollars: 1.32
};
Here is my initial solution for retrieving the value. Do you think using a for loop would be a suitable approach here?
let cur_type = document.getElementById('currencies').value; //assign the id 'currencies' to cur_type and get value
cur_type = cur_type.trim(); // remove all leading and trailing spaces in the string.
if (rates.hasOwnProperty(cur_type)) { // get the property of rates and add to cur_type
document.getElementById('exchangerate').innerHTML =
'One US Dollar buys you ' + rates[cur_type] + ' ' + rates; // get id 'exchangerate' and display in the browser the value of each property followed by the names (rates) of each property.
}
}