There are some errors in your code, let’s go by parts.
1º) To take an HTML element with the method document.getElementById()
, you must pass to it a string, which does not happen. You are passing a variable there, but this variable does not have the name of the HTML element you want to take.
2º) The same happens within the function somar()
, where, instead of a string, you pass a variable to the method document.getElementById()
. Therefore, when you pass an argument to a method without using quotation marks, the interpreter will understand that that argument is a variable, constant, function, etc. When it does not find an error, as in your code.
3º) With the method document.getElementById()
, you are trying to take the element, not the value that is inside it. To take the value of a input
, you must do document.getElementById('nomeDoElemento').value
.
That said, theoretically your code should work like this:
n1 = window.document.getElementById('n1').value;
n2 = window.document.getElementById('n2').value;
function somar() {
var n11 = Number.parseFloat(n1);
var n22 = Number.parseFloat(n2);
var result = n11 + n22;
var out1 = window.document.getElementById('out');
out1.innerHTML = `${result}`
}
<h1>Fazendo a soma</h1>
<input type="number" name="txtn1" id="n1" />
<input type="number" name="txtn2" id="n2" />
<input type="button" value="Calcular" onclick="somar()" />
<p id="out">Resultado</p>
However, it still doesn’t work as expected. We receive a NaN
(not a number) when we click the add button, because, when we click, inside the function somar()
, n1
and n2
sane null
. The reason they are null
, is that they are declared at the top of the code, and how the code is interpreted from top to bottom, when passing through that part of the code, the interpreter tries to assign the value of the input to them, BUT THE INPUT HAS NOT YET BEEN REDENRIZED.
To get around this, we can, for example, declare the variables n1
and n2
only within the function somar()
, so, when we click the add button, we will make sure that they will not receive null, since the inputs (HTML elements) have already been rendered.
Thus, the correct code is as follows:
function somar() {
var n1 = window.document.getElementById('n1').value;
var n2 = window.document.getElementById('n2').value;
var n11 = Number.parseFloat(n1);
var n22 = Number.parseFloat(n2);
var result = n11 + n22;
var out1 = window.document.getElementById('out');
out1.innerHTML = `${result}`
}
<h1>Fazendo a soma</h1>
<input type="number" name="txtn1" id="n1" />
<input type="number" name="txtn2" id="n2" />
<input type="button" value="Calcular" onclick="somar()" />
<p id="out">Resultado</p>
You have to take the values within the function and missed to put
.value
, in addition to the quotation marks as quoted in the answer below.– Sam