Zed-King Institute

    JavaScript Program to Calculate with Two Input Numbers

    hardJavaScript + formsHTML

    Reading values from a form, calculating, and showing the answer — the core of every JavaScript calculator question.

    The question

    Create two number inputs with ids "a" and "b", a button with id "calc" and a <span id="result">. When the button is clicked, show the product of the two numbers in #result (only the number).

    The code

    index.html

    <input type="number" id="a">
    <input type="number" id="b">
    <button id="calc">Calculate</button>
    <p>Result: <span id="result"></span></p>
    
    <script>
    document.getElementById("calc").addEventListener("click", function () {
      var a = Number(document.getElementById("a").value);
      var b = Number(document.getElementById("b").value);
      document.getElementById("result").textContent = a * b;
    });
    </script>

    Result

    How it works

    1. 1document.getElementById("a").value reads what was typed in the first box.
    2. 2Number(…) converts that text into a number.
    3. 3The result is written into the #result span with textContent.

    Common mistakes

    • Skipping Number(): "12" + "4" joins text and shows 124.
    • Reading .value once when the page loads instead of inside the click function.

    Now solve a similar question yourself

    A new HTML / CSS / JS question every time, checked instantly.

    Practice questions