Search code examples
javascriptfunctionparametersnumbers

Struggling with making my multiplication "calculator" work


I am struggling to make the two numbers i put in the text field multiply and show me the answer to the multiplication. Here is how it should look like when i click the multiply numbers button:(https://i.sstatic.net/WXEkm.png)](https://i.sstatic.net/WXEkm.png)

So i have tried what is shown here:

<script>
      var userInput1 = document.getElementById("user-input-1");
      var userInput2 = document.getElementById("user-input-2");
      var numbersBtn = document.getElementById("numbers-btn");
      var outputDiv = document.getElementById("output-div");

      numbersBtn.onclick = getMultiplication;

      var number1 = userInput1.value;
      var number2 = userInput2.value;

      function getMultiplication(number1, number2) {
        var result = number1 * number2;
        return result;
      }

      outputDiv.innerHTML = getMultiplication(number1, number2);
    </script>

It looks like this on the webpage:(https://i.sstatic.net/HxMCT.png)](https://i.sstatic.net/HxMCT.png)

The when i type numbers in the boxes and click the button, nothing happens and no error in the console log.

I have also tried without .value behind the userInputs, but then it displays NaN. I have also tried som other orders of the code, still no luck.

(Im very new to JS and parameters is one of my biggest weaknesses).


Solution

  • You need to get the values of number1 and number2 inside your click event

    var userInput1 = document.getElementById("user-input-1");
    var userInput2 = document.getElementById("user-input-2");
    var numbersBtn = document.getElementById("numbers-btn");
    var outputDiv = document.getElementById("output-div");
    
    numbersBtn.onclick = ()=> {
        var number1 = userInput1.value;
        var number2 = userInput2.value;  
        outputDiv.innerHTML = getMultiplication(number1, number2);
    }
    
    function getMultiplication(number1, number2) {
      var result = number1 * number2;
         return result;
    }
    <input type="number" id="user-input-1">
    <input type="number" id="user-input-2">
    <button id="numbers-btn">Multiply Numbers</button>
    <div id="output-div">0</div>

    Another way to do the same functionality

    let userInput1 = document.getElementById("user-input-1"),
        userInput2 = document.getElementById("user-input-2"),
        numbersBtn = document.getElementById("numbers-btn"),
        outputDiv = document.getElementById("output-div");
    
    numbersBtn.onclick = ()=> {
        outputDiv.innerHTML = userInput1.value * userInput2.value;
    }
    <input type="text" id="user-input-1">
    <input type="text" id="user-input-2">
    <button id="numbers-btn">Multiply Numbers</button>
    <div id="output-div">0</div>