Sum of two numbers always results in zero

Asked

Viewed 54 times

-1

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>somando valores</title>
    <style>
        *{
            font: normal 20pt arial;
        }
        div{
            width: 300px ;
            height: 100px;
            margin-top: 50px;
            background: rgb(47, 47, 255);
            color: white;
            text-align: center;
            line-height: 90px;
        }
    </style>
</head>
<body>
    <h1>somando valores</h1>
    <input type="number" name="txtn1" id="txtn1" >
    <input type="number" name="txtn2" id="txtn2" >
    <div id="somar"> somar </div>
    <p id="resultado">?</p>
    <script>
        var n1 = Number(document.getElementById('txtn1').innerHTML);
        var n2 = Number(document.getElementById('txtn2').innerHTML);
        var soma = document.getElementById('somar');
        soma.addEventListener('click', operacaoSoma);

        function operacaoSoma(){
            document.getElementById('resultado').innerHTML = n1+n2;
        }
    </script>
</body>
</html>

  • Related: https://answall.com/questions/134453/como-converter-uma-string-para-int-em-javascript

1 answer

3

You have two errors in your script, the first of which is that the tag <input> does not give its value in the property innerHTML, but on the property value, is this property you are interested in. In this case you should take the values by:

var n1 = Number(document.getElementById("txtn1").value);
var n2 = Number(document.getElementById("txtn2").value);

The second error is taking the value at the beginning of the script and not updating it, so the variables n1 and N2 will always have the values of the inputs when loading the page and not the value when pressing the button.

The corrected script looks like this:

/* Pegando a referência aos inputs */
const n1 = document.getElementById("txtn1");
const n2 = document.getElementById("txtn2");

/* Adicionando evendo ao botão */
const soma = document.getElementById("somar");
soma.addEventListener("click", operacaoSoma);

function operacaoSoma() {
  /// Pegando os valores no momento do click
  const input1 = Number(n1.value);
  const input2 = Number(n2.value);

  /// Mostrando a soma
  document.getElementById("resultado").innerHTML = input1 + input2;
}
* {
  font: normal 20pt arial;
}
div {
  width: 300px;
  height: 100px;
  margin-top: 50px;
  background: rgb(47, 47, 255);
  color: white;
  text-align: center;
  line-height: 90px;
}
<h1>somando valores</h1>
<input type="number" name="txtn1" id="txtn1">
<input type="number" name="txtn2" id="txtn2">
<div id="somar"> somar </div>
<p id="resultado">?</p>

  • Thank you so much for your help, I had tried in many ways and n had worked out kkk ;-;

Browser other questions tagged

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