Getting value from Combobox to match with Object Properties

Viewed 23

I'm trying to develop a simple currency conversion using JavaScript. I have created object with list of Currency and their exchange rate. User will select the currency they want, enter amount to convert and it will be converted into MYR. But I have problem getting the user's selection to match with my object. My code are as follows:

<h1>Currency Conversion</h1>
<div>
   <label>Select currency to convert with MYR: </label>
   <select id="CurrencyName">
      <option value="USD">USD</option>
      <option value="JPY">JPY</option>
      <option value="GBP">GBP</option>
   </select>
   <label>Enter the amount you want to convert: </label>
   <input type="number" id="amountConvert" name="convertAmount">
   <button onclick="convertCurrency()">Convert</button>
</div>
   <p id="convertAmount"></p>


let conversionRate = { USD: 4.2, JPY: 0.26, GBP: 5 };


function convertCurrency() {
   let selectedCurrency = document.getElementById("CurrencyName").value;
   let userSelection = selectedCurrency.value;
   let userAmount = document.getElementById("amountConvert").value;
   ConvertedAmount = userAmount * conversionRate.userSelection;
   document.getElementById("convertAmount").innerHTML = "You get " + ConvertedAmount + selectedCurrency;
   console.log(conversionRate.selectedCurrency);
}
1 Answers

1) When accessing the dynamic property you need to put it in [] i.e

conversionRate[selectedCurrency]

2) You've already extracted the value in

document.getElementById("CurrencyName").value

so no need to

get the value again (which will give it undefined)

let userSelection = selectedCurrency.value;

let conversionRate = {
  USD: 4.2,
  JPY: 0.26,
  GBP: 5
};

function convertCurrency() {
  let selectedCurrency = document.getElementById("CurrencyName").value;
  // let userSelection = selectedCurrency.value;
  let userAmount = document.getElementById("amountConvert").value;
  ConvertedAmount = userAmount * conversionRate[selectedCurrency];
  document.getElementById("convertAmount").innerHTML = "You get " + ConvertedAmount + selectedCurrency;
}
<h1>Currency Conversion</h1>
<div>
  <label>Select currency to convert with MYR: </label>
  <select id="CurrencyName">
    <option value="USD">USD</option>
    <option value="JPY">JPY</option>
    <option value="GBP">GBP</option>
  </select>
  <label>Enter the amount you want to convert: </label>
  <input type="number" id="amountConvert" name="convertAmount">
  <button onclick="convertCurrency()">Convert</button>
</div>
<p id="convertAmount"></p>

Related