Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

76
Visualizações
Input tag not giving correct output

What I want is, on button click the sum of value in two input texts should be consoled, but for Any value for two input texts that I give, it always gives 0,0 as output, what am I doing wrong? And since both of them are 0, their sum is also becoming 0. HTML

<!DOCTYPE html>
<html>
<head>
    <title>WeB </title>
</head>
<body>
    <input type="number" id = "num1" >
    <input type="number" id = "num2" >
    <button id = "add">+</button>
    <script src = "app.js"></script>
</body>
</html>

JS

let num1 = Number(document.getElementById('num1').value)
let num2 = Number(document.getElementById('num2').value)

document.getElementById("add").addEventListener("click",function(){
    console.log(num1,num2);
    console.log(num1+num2);

})
about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

You need to get the latest value of the input on click of the button

document.getElementById("add").addEventListener("click", function() {

  let num1 = Number(document.getElementById('num1').value)
  let num2 = Number(document.getElementById('num2').value)


  console.log(num1, num2);
  console.log(num1 + num2);

})
<input type="number" id="num1">
<input type="number" id="num2">
<button id="add">+</button>

about 4 years ago · Juan Pablo Isaza Relatório

0

This is the order of events:

  1. You read the values of the inputs (empty strings) and convert them to numbers (0) then store them in variables
  2. You bind an event listener to add those numbers together when something is clicked
  3. You type something into the inputs
  4. You click the button which
    1. Logs the values of the variables
    2. adds the values of the variables together

The variables still contain the values from the time you read the inputs

You need to move step 1 so it goes inside step 4 (i.e. inside the function you use as the event listener)

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda