'parseInt return NaN when take value from input box
i am trying to add 2 number as value from input form. typeof(parseInt(value1)) and typeof(parseInt(value2)) return number but parseInt(value1)+parseInt(value2) return NaN. please someone explain
var input1 = document.getElementById('num1')
var input2 = document.getElementById('num2')
var value1 = input1.value
var value2 = input2.value
btn.addEventListener('click', myfunc)
function myfunc() {
alert(typeof(parseInt(value1)))
alert(typeof(parseInt(value2)))
alert(parseInt(value1)+parseInt(value2))
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Tính toán</title>
</head>
<body>
<form action="">
<div>
<label for="num1">Number 1</label>
<div>
<input type="number" name="num1" id="num1" />
<span class="error" id="errNum1">(*)</span>
</div>
</div>
<div>
<label for="num2">Number 2</label>
<div>
<input type="number" name="num2" id="num2" />
<span class="error" id="errNum2">(*)</span>
</div>
</div>
<div></div>
<div>
<input type="button" value="Tính toán" id="btn" />
</div>
</form>
<script src="js.js"></script>
</body>
</html>
Solution 1:[1]
You get the value of the inputs when the page is loaded, so they will always be empty. Instead you want to get the values when the button is clicked.
btn.addEventListener('click', myfunc)
function myfunc() {
var input1 = document.getElementById('num1')
var input2 = document.getElementById('num2')
var value1 = input1.value
var value2 = input2.value
alert(typeof(parseInt(value1)))
alert(typeof(parseInt(value2)))
alert(parseInt(value1)+parseInt(value2))
}
Solution 2:[2]
The correct way to do that:
You don't need to use parseInt() on input type= number,
just use valueAsNumber property
const myForm = document.forms['my-form']
myForm.btn.onclick = evt =>
{
console.clear()
console.log(typeof myForm.num1.valueAsNumber)
console.log(typeof myForm.num2.valueAsNumber)
console.log( myForm.num1.valueAsNumber + myForm.num2.valueAsNumber )
}
label
, button {
display : block;
margin : .3em;
}
<form action="" name='my-form'>
<label>
Number 1
<input type="number" name="num1" value="0" >
</label>
<label>
Number 2
<input type="number" name="num2" value="0" >
</label>
<button name="btn" type="button"> Tính toán </button>
</form>
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Henry |
| Solution 2 | Mister Jojo |
