loader image

JavaScript calculator program

Design a form that accepts two integers. Provide 4 buttons for Add, Subtract, Multiply, Divide. Add JavaScript program to add, subtract, multiply and divide the given numbers when these buttons are clicked. Use output element to display the results

<html>

<head>
    <script>
        function add() {
            var a = parseInt(document.getElementById('a').value);
            var b = parseInt(document.getElementById('b').value);
            r = a + b;
            document.getElementById("result").innerHTML = a + " + " + b + " = " + r;
        }

        function sub() {
            var a = parseInt(document.getElementById('a').value);
            var b = parseInt(document.getElementById('b').value);
            r = a - b;
            document.getElementById("result").innerHTML = a + " - " + b + " = " + r;
        }

        function mul() {
            var a = parseInt(document.getElementById('a').value);
            var b = parseInt(document.getElementById('b').value);
            r = a * b;
            document.getElementById("result").innerHTML = a + " * " + b + " = " + r;
        }

        function div() {
            var a = parseInt(document.getElementById('a').value);
            var b = parseInt(document.getElementById('b').value);
            r = a / b;
            document.getElementById("result").innerHTML = a + " / " + b + " = " + r;
        }
    </script>
</head>

<body>

    <h1>Calculator</h1>
    <form>
        Enter number 1:
        <input type="text" id="a" /><br />
        Enter number 2:
        <input type="text" id="b" /><br />
        <input type="button" value="Add" onClick="add()" />
        <input type="button" value="Subtract" onClick="sub()" />
        <input type="button" value="Multiply" onClick="mul()" />
        <input type="button" value="Divide" onClick="div()" />
    </form>
    <p id="result"></p>


</body>

</html>
Output
calculator
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments