I’m trying to make a simple calculator, however, when I try to add two numbers, I’m getting the NaN
result.
Before this problem, the function sumar()
was returning [object HTMLInputElement][object HTMLInputElement]
, however after adding +
when calling the dom, it returns NaN
.
HTML File
<body>
<form>
<div>
<label for="op1">Ingrese un numero</label>
<input type="number" value="0" id="op1"/>
</div>
<div>
<label for="op2">Ingrese otro numero</label>
<input type="number" value="0" id="op2"/>
</div>
</form>
<div id="resultado">0</div>
<button onclick="sumar()">Sumar</button>
<script src="./script.js"></script>
</body>
JS file
const sumar = ()=> {
const op1 = +document.getElementById("op1");
const op2 = +document.getElementById("op2");
document.getElementById("resultado").innerHTML = op1 + op2;
}
3
Answers
Make sure you are not receiving string values . try using
You need to get the value of the elements
And
parseInt()
orparseFloat()
to remove the errorIn your javascript file, try to replace your code with this
i’ve try in playcode.io, and that’s work well.