Skip to content
Forum Navigation
You need to log in to create posts and topics.

Simple calculator using javascript.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <form>
        <input type="text" name="" id="firstInput">
        <select name="" id="operators">
            <option value="add">+</option>
            <option value="sub">-</option>
            <option value="mul">x</option>
            <option value="div">/</option>
        </select>
        <input type="text" name="" id="secondInput">
        <input type="button" value="submit" onclick="calculator()">
        <h3 id="ans"></h3>
    </form>
</body>
<script>
    function calculator(){
        var firstInput = document.getElementById('firstInput').value;
        var secondInput = document.getElementById("secondInput").value;
        var operators = document.getElementById('operators').value;
        var ans = document.getElementById('ans');
        console.log(operators);
        function addition(){
            let x = parseFloat(firstInput);
            let y = parseFloat(secondInput);
            if (isNaN(x) || isNaN(y)) alert("Please enter valid numbers!");
            // else return x + y
            ans.innerHTML="ans"+" = "+(x+y);
            console.log(x + y);
        }
        function subtract(){
            let x = parseFloat(firstInput);
            let y = parseFloat(secondInput);
            if (isNaN(x) || isNaN(y)) alert("Please enter valid numbers!");
            ans.innerHTML="ans"+" = "+(x-y);
            console.log(x - y);
        }
        function multiply(){
            let x = parseFloat(firstInput);
            let y = parseFloat(secondInput);
            if (isNaN(x) || isNaN(y)) alert("Please enter valid numbers!");
            ans.innerHTML="ans"+" = "+(x*y);
            console.log(x * y);
        }
        function division(){
            let x = parseFloat(firstInput);
            let y = parseFloat(secondInput);
            if (isNaN(x) || isNaN(y)) alert("Please enter valid numbers!");
            ans.innerHTML="ans"+" = "+(x/y);
            console.log(x / y);
        }
        if(operators == "add"){
            addition();
        }else if(operators == "sub"){
            subtract();
        }else if(operators == "mul"){
            multiply();
        }else{
            division();
        }
    }
</script>
</html>
Uploaded files:
  • Capture.PNG
Suniti Singh has reacted to this post.
Suniti Singh

Screenshot