'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);
})
Solution 1:[1]
This is the order of events:
- You read the values of the inputs (empty strings) and convert them to numbers (0) then store them in variables
- You bind an event listener to add those numbers together when something is clicked
- You type something into the inputs
- You click the button which
- Logs the values of the variables
- 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)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Quentin |
