First project - save numeric value in variable

Hello everybody,
I have done the first couple HTML, CSS, and Javascript courses. They are great by the way and help me a lot to learn. Now, I am working on my very first project, to check if I understood everything I have learnt so far.

I try to program a simple calculator and want to save a numeric value from a textbox into a variable. I do something wrong as it doesn’t work.

I could identify the problem are the lines where I try to overwrite the value in amountCad and exchangeRate variables. However, I am not sure what I have to do to make it work. Can somebody please point me in the right direction?

Any help is appreciated.
Thank you.


const amountCadText = document.getElementById("amountCadText");
const exchangeRateText = document.getElementById("exchangeRateText");
const amountUsdText = document.getElementById("amountUsdText");
const button1 = document.getElementById("calculateButton");

/*Initial variables*/
let amountUsd = 0;
let exchangeRate = 2;
let amountCad = 500;

/*override initial values with values in textbox*/
amountCad = amountCadText.innerText;
exchangeRate = exchangeRateText.innerText;

/*calculate USD*/
function calculate() {
  amountUsd = amountCad * exchangeRate;
  amountUsdText.innerText = amountUsd;
 }

*/event when clicking on button/*
button1.addEventListener("click", calculate);

MY HTML Code:

    <div class="input">
      <label for="amountCadText">Amount in CAD:</label>
      <input ID="amountCadText" type="number" min="0" value="100" required></input> 
      <label for="exchangeRateText">Exchange rate (CAD/USD):</label>
      <input ID="exchangeRateText" type="number" min="0" value="1.55" required></input>
      <label for="amountUsdText">Amount in USD:</label>
      <span ID="amountUsdText">XX</span>
      <button ID="calculateButton" type="button">Calculate</button>
      <button ID="clear" type="button">clear</button>
      </div>

That’s not a proper block quote like the others. A line comment starts with two backslashes. A block quote has a backslash followed by a star. Then your text. Closing it is a start followed by a backslash. Like the others.

Secondly you can’t do math on strings directly. They have to be numbers. The innerText property isn’t going to work. However there is a way to get the value from those elements properly. Either you find a method that returns the raw value or you parse your input into a number.

A method on the Number`class can you help translate the value.

Otherwise you can look at the documentation for number input nodes.

Let me know if you need any further clarification.

1 Like

Thank you for the quick answer. I changed the code and it worked.

function calculate() {
  amountCad = amountCadText.value;
  exchangeRate = exchangeRateText.value;
  amountUsd = amountCad * exchangeRate;
  amountUsdText.innerText = amountUsd;
}