Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

adding two numbers with html/JS not working

I have this extremely simple code for adding 2 numbers with JS and just showing the result to the console but it’s not working. I tried all day to figure out what’s wrong but I really don’t know…

<!DOCTYPE html>
<html>

<head>
    <title>Failure</title>
</head>

<body>
    <label for="value1">Value1</label>
    <input type="number" id="value1" />
    <label for="value2">Value2</label>
    <input type="number" id="value2" />
    <button id="btn">Submit</button>
    <hr>
    <h2>Result</h2>
    <p id="result"></p>

    <script>
        let a = document.getElementById("value1").value;
        let b = document.getElementById("value2").value;
        let result = document.getElementById("result");
        let button = document.getElementById("btn");
        function summing() {
            let sum = a + b;
            console.log(sum);
        }
        button.addEventListener("click", summing);
    </script>
</body>

</html>

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

You need to call .value inside the listener function, as a and b do not change when the input value changes.

This is because the .value gets the value at the instant the line is run; but because it is outside the callback, it is run once, on page load, when the inputs are empty.

Also you need to parseInt the value, as it returns a string, even for number inputs.

<!DOCTYPE html>
<html>

<head>
    <title>Failure</title>
</head>

<body>
    <label for="value1">Value1</label>
    <input type="number" id="value1" />
    <label for="value2">Value2</label>
    <input type="number" id="value2" />
    <button id="btn">Submit</button>
    <hr>
    <h2>Result</h2>
    <p id="result"></p>

    <script>
        let a = document.getElementById("value1");
        let b = document.getElementById("value2");
        let result = document.getElementById("result");
        let button = document.getElementById("btn");
        function summing() {
            let sum = parseInt(a.value) + parseInt(b.value);
            console.log(sum);
        }
        button.addEventListener("click", summing);
    </script>
</body>

</html>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading