Sum does not present the expected result

Asked

Viewed 70 times

0

I created a simple calculator with HTML5, CSS and Javascript. However, when I calculate, the value of the first field is added to itself, and not to the second field. Therefore, when I perform the calculation of 4 + 7, the result gives (8)?

Follows the code:

<!DOCTYPE html>
<html lang="pt-br">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Calculator</title>
    <style>
        body {
            font: normal 15pt Arial;
        }

        input {
            width: 100px;
            border-radius: 2px;
        }

        div#res {
            margin-top: 20px;
        }

        button {
            background-color: green;
            color: white;
        }
    </style>
</head>

<body>
    <h3> SOMANDO NÚMEROS </h3>
    <input type="number" name="txtn1" id="txtn1"> +
    <input type="number" name="txtn2" id="txtn2">
    <input type="button" value="Somar" onclick="somar()">
    <div id="res">Resultado:</div>

    <script>
        function somar() {
            var tn1 = window.document.getElementById('txtn1')
            var tn2 = window.document.getElementById('txtn2')
            var res = window.document.getElementById('res')
            var n1 = Number(tn1.value)
            var n2 = Number(tn1.value)
            var s = n1 + n2
            res.innerHTML = `A soma entre ${n1} e ${n2} é igual a ${s}`
        }
    </script>
</body>

</html>

  • Did the answer solve your question? Do you think you can accept it? See [tour] if you don’t know how you do it. This would help a lot to indicate that the solution was useful for you. You can also vote on any question or answer you find useful on the entire site (when you have 15 points).

1 answer

1

The result of your code already hints at the error. It says that "the sum of 4 and 4 equals 8", so you are not reading your screen. Then it is clear that you are taking the same number, the first typed and adding them up.

This code is too complex and so it probably got lost because of this, look at this excerpt:

var n1 = Number(tn1.value)
var n2 = Number(tn1.value)

I put in the Github for future reference.

The two variables are being initialized with the same data, so you use the two to add.

Simplify the code and you won’t have problems so easily.

  • Wow! Dear Maniero, really, the two variables were on the same die. Thank you very much, tbm for the tip. I’ll try to simplify the code. Success for you, partner! =)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.