Lucas
Lucas

Reputation: 57

How to get the value number in the javascript object?

I am building a web form for a currency exchange example. Here is sample HTML and Javascript which I have coded initially.

<!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>

Sorry for the noobie question. I am trying to store the currency data in a JS collection and want to have a down menu. How should I get the value from the object to display in the dropdown menu?

I have been trying to store the data inside a object but it seems not working the way it should. Also want to check if single quotes correct way for a variable -- the only way I found working.

let rates = {
    UKPounds: 0.75,
    Euros: 0.9,
    Yen: 109.44,
    Yuan: 7.02,
    SwissFrancs: 0.98,
    CanadianDollars: 1.32
  };

Below is my first solution to get the value. Do you guys think it would be appropriate to use the for loop in 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 the leading and the 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 dislay in the browser the value of each property following by the names (rates) of each property.
  }
}

Upvotes: 0

Views: 144

Answers (1)

symlink
symlink

Reputation: 12218

You were almost there:

const rates = {
  "UK Pounds": 0.75,
  "Euros": 0.9,
  "Yen": 109.44,
  "Yuan": 7.02,
  "Swiss Francs": 0.98,
  "Canadian Dollars": 1.32
}

function getCurrency() {
  let cur_type = document.getElementById('currencies').value.trim()
  let msg = cur_type ? "One US Dollar buys you " + rates[cur_type] + " " + cur_type : ""
  document.getElementById("exchangerate").innerHTML = msg
}
<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>

Upvotes: 1

Related Questions