Why is there not assigned value in the line val3.value = parseInt(val1.value + val2.value);
the specified value "NaN" cannot be parsed, or is out of range?
var val1 = parseInt(document.getElementById("num1"));
var val2 = parseInt(document.getElementById("num2"));
var val3 = document.getElementById("num3");
document.getElementById("add").addEventListener("click", function() {
val3.value = parseInt(val1.value + val2.value);
});
<input type="number" id="num1" />
<input type="number" id="num2" />
<input type="number" readonly id="num3" /> <br />
<button id="add">add</button>
the output value not assigned
3
Answers
Replace the script with the following :
You can use the following:
Your code has some fatal flaws:
HTMLInputElement
s as a string which won’t work and it’s not what you want to dovalue
s of inputs are) using+
the values will be concatenated, not added meaning"2" + "2"
will be"22"
, not4
.To address this you want to do two things:
parseInt()
on the HTML elementsvalueAsNumber
instead ofvalue
since this will give you the value of the<input />
element as anumber
hence eliminating the need to manually parse the number and doing a concatenation instead of an addition.Last but not least, generally, consider using
const
orlet
instead ofvar
, sincevar
always declares global variables, which you can cause all kinds of weird problems and bugs once your program grows in size. See Difference between var, let and const keywords in JavaScriptYou’re trying to parse the element itself, not its value, also you’re concatenating the values as strings before parsing them to integers