1

So here is the thing I'm trying to create a simple example of a calculator with JavaScript, but the problem is that the function is not getting the numbers . Here is The code, I want to know what I've done wrong and if there is any Mistakes I hope you correct me. PS: I'm new to JavaScript I just started learning

 <!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Calculator</title>
    <script>
        //Acessing Elements
        var x = parseInt(document.getElementById("x"));
        var y = parseInt(document.getElementById("y"));
        var result ;

        //Declaring Functions
        function add(){
            result = x + y;
        }
        
    </script>
</head>
<body>
    
        <fieldset>
            <label for="first">First Number</label><br>
            <input type="number" id="x"><br>
            <label for="second">Second Number</label><br>
            <input type="number" id="y"><br>
            <input type="button" value="+" onclick="add();">
            <input type="button" value="-" onclick="substract();">
            <input type="button" value="*" onclick="multiplier();">
            <input type="button" value="/" onclick="division();"><br>
            <label id="result"></label><br>
            <script>
                document.getElementById("result").innerHTML = result;
            </script>
        </fieldset>
    
</body>
</html>
  • 1
    you are trying to parseInt the elements themselves and not their values, which you get through their `.value` property. You also try to get them before they exist, move your script to before the ending `

    ` tag

    – Patrick Evans Sep 05 '21 at 17:11
  • There are 3 mistakes. Let me just write an answer – Krokodil Sep 05 '21 at 17:13
  • The question was closed incorrectly. Even if the OP checks the links which apparently "have answers" they will still not be able to gain enough answers to build what they are after. Furthermore this question shows that the OP tried to code the calculator, and asked here as their last resort. I believe this question should not be closed. – Krokodil Sep 05 '21 at 17:16
  • Heres a fiddle even though this question is now closed https://jsfiddle.net/seLtxj2n/23/ –  Sep 05 '21 at 17:19
  • https://jsfiddle.net/douscriptist/ajndLtz9/1/ Similar to your logic/code (not saying its best practice but it ok for learning purposes). – dogukyilmaz Sep 05 '21 at 17:26
  • @Zakaria Bhaibi have a look at this link: https://jsfiddle.net/z5mgq40k/2/. In the link you will find the explanation of your errors, and how to correct them. I have also included the now-working code. – Krokodil Sep 05 '21 at 17:48

0 Answers0