Here is my Javascript file prompt.js:
let a = parseFloat(document.getElementById("num1").value);
let b = parseFloat(document.getElementById("num2").value);
function getSum() {
var sum = a + b;
document.getElementById("output").value = sum;
}
answerBtn.addEventListener('click', getSum);
and here is the corresponding html file:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<form>
<div>
<label for="num1">Enter a number A: </label>
<input type="text" id="num1" />
</div>
<div>
<label for="num2"> Enter another number B: </label>
<input type="text" id="num2" />
</div>
<input type="button" value="A + B" id = "answerBtn" >
<br>
<div>
<input type="text" id="output" readonly/>
</div>
</form>
<script src="interaction-simple.js" defer></script>
</body>
</html>
So there are two text fields in the page in which the user enters a number and the sum of the number is calculated upon clicking the button and the result is displayed in another text field just below the button.
When i enter the numbers the output is : NaN
in the output text field.
What’s wrong with my code?
3
Answers
If you declare the variables inside the
getSum
function they are populated when called rather than at page load, like so:Your a and b variables are initialized before the data is actually provided to text field. So the right solution is to gather data when the event is emitted and not when page is loaded. You can use @Professor Abronsius’s code or alternativly you can define a and b as text fields and not their value, then inside the sum function access the data.
Actually,
Here is the issue in the script where you try to access the value of input fields.
Just try to access the value of the input field with the click of the (CTA) button.
Just refactored a bit & added handling for invalid inputs.