I started learning programming a little while ago, but I got stuck on the functions and intervals part.
What I wanted was a very simple system, to do multiplication, using HTML and JavaScript, passing the input numbers as parameters.
However, when I run the code, it returns NaN as the result.
let button = document.querySelector("#button");
let num1 = parseInt(document.getElementById('num1').value);
let num2 = parseInt(document.getElementById('num2').value);
function operacao(a, b) {
let resp = a * b;
return resp;
}
let resto = operacao(num1, num2)
button.addEventListener("click", function() {
document.getElementById('resto').innerHTML = 'O resultado é: ' + resto
});
<label>
Informe os numeros:
<br>
<input type="number" id="num1">
<p>x</p>
<input type="number" id="num2">
</label>
<br>
<br>
<button id="button" onclick=(operacao)>Multiplicar</button>
<p id="resto"></p>
3
Answers
You’re reading the values from the inputs and performing a calculation on them immediately upon loading the page, before the user has had a chance to enter any values:
Instead, read the values from the input and perform the calculation in the button click handler:
You need to get the value of the inputs after clicking of the button. In your code the value of
num1
&num2
will be undefined aslet num1 = parseInt(document.getElementById('num1').value); let num2 = parseInt(document.getElementById('num2').value);
are executing before the button click and those inputs are initially emptyYou are encountering with NaN (Not-a-Number) result because you are trying to get the values of the input fields before the user has had a chance to enter anything. Values of num1 and num2 are NaN because you are calling the parseInt function immediately when the script loads and at that time, the input fields are empty.
To fix this, you need to get the values of the input fields when the button is clicked, not when the script initially runs.
I am providing the code below for your reference:
I hope this code will resolve your issue.