Simple calculator not working

Im trying many things to make this calculator to work but it just wont, no matter what i change or try it’s not doing anything. Any help would be appreciated.

HTML code:

<!DOCTYPE html>
<html lang="en">
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="style.css" type="text/css">
    <div id="calculator">
        <div id="inputs">
            <div class="inputValues"><p>Input first number:</p><input class="input" type="text" id="firstNumber"></div>
            <div class="inputValues"><p>Input second number:</p><input class="input" type="text" id="secondNumber"></div>
        <div id="operations">
            <button onclick="calculate(1);">+</button>
            <button onclick="calculate(2);">-</button>
            <button onclick="calculate(3);">*</button>
            <button onclick="calculate(4);">/</button>
        <div id="result">
            <p>Result: </p><input class="input" type="text" id="resultValue"  readonly="readonly">
    <script src="script.js"></script>

JS code:

function calculate(operator) {
     var firstNumber = parseInt(document.getElementById("firstNumber").value);
     var secondNumber = parseInt(document.getElementById("secondNumber").value);
     var resultValue = parseInt(document.getElementById("resultValue").value);
     var result = 0;
     switch(operator) {
          case 1:
               result = firstNumber + secondNumber;
          case 2:
               result = firstNumber - secondNumber;
          case 3:
               result = firstNumber * secondNumber;
          case 4:
               result = firstNumber / secondNumber;
               alert("Invalid operator");

     resultValue = result;

If you do a log, you will see the problem is with displaying the result:

resultValue = result;
console.log(firstNumber, secondNumber, result, resultValue);

To resolve this, replace declaration/assignment where appropriate:

var resultValue = document.getElementById("resultValue");
var result;

resultValue.value = result;

Or you can remove the resultValue declaration, and assign the result directly, thus:

document.getElementById("resultValue").value = result;

1 Like

Thank you, i solved the problem. Looks like i was catching input values immedietly when script loaded, so i had to use values inside function not outside of it but only use declarations outside functions.

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.