I have this extremely simple code for adding 2 numbers with JS and just showing the result to the console but it’s not working. I tried all day to figure out what’s wrong but I really don’t know…
<!DOCTYPE html>
<html>
<head>
<title>Failure</title>
</head>
<body>
<label for="value1">Value1</label>
<input type="number" id="value1" />
<label for="value2">Value2</label>
<input type="number" id="value2" />
<button id="btn">Submit</button>
<hr>
<h2>Result</h2>
<p id="result"></p>
<script>
let a = document.getElementById("value1").value;
let b = document.getElementById("value2").value;
let result = document.getElementById("result");
let button = document.getElementById("btn");
function summing() {
let sum = a + b;
console.log(sum);
}
button.addEventListener("click", summing);
</script>
</body>
</html>
>Solution :
You need to call .value inside the listener function, as a and b do not change when the input value changes.
This is because the .value gets the value at the instant the line is run; but because it is outside the callback, it is run once, on page load, when the inputs are empty.
Also you need to parseInt the value, as it returns a string, even for number inputs.
<!DOCTYPE html>
<html>
<head>
<title>Failure</title>
</head>
<body>
<label for="value1">Value1</label>
<input type="number" id="value1" />
<label for="value2">Value2</label>
<input type="number" id="value2" />
<button id="btn">Submit</button>
<hr>
<h2>Result</h2>
<p id="result"></p>
<script>
let a = document.getElementById("value1");
let b = document.getElementById("value2");
let result = document.getElementById("result");
let button = document.getElementById("btn");
function summing() {
let sum = parseInt(a.value) + parseInt(b.value);
console.log(sum);
}
button.addEventListener("click", summing);
</script>
</body>
</html>