skip to Main Content

This is my code:

<!DOCTYPE html>
<html lang="de">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Währungsrechner</title>
    <link rel="stylesheet" href="style.css">
</head>

<script>
    function calc(){
   let euro = euro.value;
   let result = euro * 1.1;
   usd.value = result;
}
</script>

<body>
    <div></div>
<form>
    <h1>WÄHRUNGSRECHNER</h1>
    <div></div>
    <div>
      <input id="euro" value="0,00" type="text">
      <label>EUR</label>
    </div>
    <div>
      <input id="usd" value="0,00">
      <label>USD</label>
    </div>
</form>
    <button onclick="calc()">Berechnen</button>
</body>

If I click on the button it says "Uncaught ReferenceError: Cannot access ‘euro’ before initialization" but why???

If I click on the button it should take the number from my first input field, multiply it with 1,1 and the show it in the second input field.

2

Answers


  1. Chosen as BEST ANSWER

    I got it on my own. I just had to change the javascript code to:

    function calc() {
      let result = euro.value * 1.1;
      usd.value = result;
    }
    

  2. The issue is because you have an element with an id of euro, so that is what the euro is a reference to. This is because you haven’t explicitly declared the variable, so the document object is checked to find a matching property, which it will as element ids are set as properties there. This is a very annoying legacy behaviour. Due to this JS gets confused whether you’re trying to reference document.euro or the euro variable.

    To fix the problem, and improve the quality of your code, explicitly define the variables and use unobtrusive event handlers outside of the HTML.

    In addition, for mathematical operations you will need to use . as the decimal separator for JS to function correctly. You can use globalisation methods to return this back to using , in the output:

    const euro = document.querySelector('#euro');
    const usd = document.querySelector('#usd');
    
    document.querySelector('#calc').addEventListener('click', () => {
      var eur = parseFloat(euro.value.replace(",",""));
      let result = eur * 1.1;
      usd.value = result.toLocaleString('fr', { // amend culture code as needed
        minimumFractionDigits: 2
      });
    });
    <div></div>
    <form>
      <h1>WÄHRUNGSRECHNER</h1>
      <div></div>
      <div>
        <input id="euro" value="0,00" type="text">
        <label>EUR</label>
      </div>
      <div>
        <input id="usd" value="0,00">
        <label>USD</label>
      </div>
    </form>
    <button id="calc">Berechnen</button>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search