-2

Estou estudando Javascript, e durante esse exemplo me deparei com um erro que não consegui resolver.

<!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>Somando Números</title>
</head>
<body>
    <h1>Somando Valores</h1>
    <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() {
            let tn1 = window.document.getElementById('txtn1')
            let tn2 = window.document.getElementById('txtn2')
            let res = window.document.getElementById('res')
            let n1 = Number(tn1.value)
            let n2 = Number(tn2.value)
            let s = n1 + n2
            res.innerHTML = `A soma entre ${tn1} e ${tn2} é ${res}`
        }
    </script>
</body>
</html>

Ao somar os números, o resultado que me aparece é isto:

" A soma entre [object HTMLInputElement] e [object HTMLInputElement] é [object HTMLDivElement]

1
  • 6
    Será que o que você quiz fazer não era res.innerHTML = `A soma entre ${n1} e ${n2} é ${s}` ?
    – Andre
    28/07/2019 às 3:03

1 Resposta 1

5

O problema não é a soma e sim o que você está somando.

tn1 e tn2 são referências para os inputs:

let tn1 = window.document.getElementById('txtn1')
let tn2 = window.document.getElementById('txtn2')

res é referencia para um div:

let res = window.document.getElementById('res')

O curioso é mais adiante no código você definiu n1 e n2 que são os valores dos input:

let n1 = Number(tn1.value)
let n2 = Number(tn2.value)

Também definiu s que é o resultado da soma:

let s = n1 + n2

Então para reparar o seu código basta colocar a linha:

res.innerHTML = `A soma entre ${n1} e ${n2} é ${s}`

no lugar de:

res.innerHTML = `A soma entre ${tn1} e ${tn2} é ${res}`

function somar() {
  let tn1 = window.document.getElementById('txtn1');
  let tn2 = window.document.getElementById('txtn2');
  let res = window.document.getElementById('res');
  let n1 = Number(tn1.value);
  let n2 = Number(tn2.value);
  let s = n1 + n2;
  // Aqui foi feita a modificação
  res.innerHTML = `A soma entre ${n1} e ${n2} é ${s}`;
}
<!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>Somando Números</title>
</head>

<body>
  <h1>Somando Valores</h1>
  <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>

</body>

</html>

4
  • @AngustiVasques Uma sugestão para diminuir o código:let n1 = +tn1.value; let n2 = +tn2.value; 28/07/2019 às 4:25
  • 3
    @MauryDeveloper Dependendo do que for digitado, nem sempre o + funciona da mesma maneira: stackoverflow.com/a/17106701 - E existe ainda a opção de usar parseInt, que também tem diferenças em alguns casos: stackoverflow.com/q/4090518 - Claro que se for digitado um número válido, tanto faz, mas dependendo de como vc quer tratar os casos especiais, faz diferença (e aí vc usa o que faz sentido, pois não é só porque o código ficou menor que necessariamente ficou "melhor")
    – hkotsubo
    28/07/2019 às 15:51
  • Bom, obrigado à todos que ajudaram.
    – mrMashiron
    29/07/2019 às 12:19
  • 3
    @MauryDeveloper Sobre "código menor não ser necessariamente melhor": pt.stackoverflow.com/a/400495/112052
    – hkotsubo
    30/07/2019 às 13:25

Esta não é a resposta que você está procurando? Pesquise outras perguntas com a tag .