What is the error in the script to generate the calculation?

Asked

Viewed 53 times

-2

<!DOCTYPE html>
<html lang="pt-br">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="css/style.css">
    <link rel="shortcun icon" href="imagem/contador.ico">
    <title>Contador de Pessoas</title>

</head>

<body>
    <h1>Contador de Pessoas</h1>
    
    <div class="entrada">
       <h3>Entrada</h3> 
       <input type="number" name="entrada" id="entrada">
           
    </div>

    <div class="saida">
        <h3>Saída</h3>
        <input type="number" name="saida" id="saida">     

    </div>
    <input type="button" value="Total" onclick="somar">
    <p id="res">Total de Pessoas no dia:</p>
   
    <script>
        function somar(){
        var entrada = window.document.querySelector("input#entrada");
        var saida = window.document.querySelector("input#saida");
        var resultado = window.document.getElementsById("res");
        var num1 = Number(entrada.value);
        var num2 = Number(saida.value);
        var resultado = num1 - num2;
        res.innerHTML = resultado;
        }
    </script>
    
</body>
</html>

  • It has two errors: 1 - the correct is onclick="sum()" ::::: 2 - getElementById without the s

2 answers

2


Has two mistakes:

  1. the correct is onclick="somar()"
  2. getElementById without the s

        function somar(){
        var entrada = window.document.querySelector("input#entrada");
        var saida = window.document.querySelector("input#saida");
        var resultado = window.document.getElementById("res");
        var num1 = Number(entrada.value);
        var num2 = Number(saida.value);
        var resultado = num1 - num2;
        res.innerHTML = "Total de Pessoas no dia: " +resultado;
        }
<p id="res">Total de Pessoas no dia:</p>
<div class="entrada">
       <h3>Entrada</h3> 
       <input type="number" name="entrada" id="entrada">   
</div>

<div class="saida">
        <h3>Saída</h3>
        <input type="number" name="saida" id="saida">  <input type="button" value="Total" onclick="somar()">   
</div>
    
    

  • Thank you, it was lack of attention. Beginner’s mistake.

1

The error of your question is in assigning the result in a Element that you did not declare.

I’ll pass the correction:

function somar(){
    var entrada = window.document.querySelector("#entrada");
    var saida = window.document.querySelector("#saida");

    var num1 = Number(entrada.value);
    var num2 = Number(saida.value);
    var resultado = num1 - num2;

    var res = document.getElementById("res");
    res.innerText += resultado;
}

Also in the attribute that calls the function. The correct is <input type="button" value="Total" onclick="somar()">.

Browser other questions tagged

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