this my code and I can't seem to find out why it returns NaN. I tried just given it a certain number in the addnum function but that also didn't work.
<script>
var output = document.getElementById("output");
var input = document.getElementById("input").value;
var int_input = parseInt(input);
function addnum(N) {
int_input = int_input + N;
output.innerHTML = int_input;
}
document.getElementById("addinput").addEventListener("keyup", function (event) {
if (event.keyCode == 13) {
addnum(6);
}
})
</script>
When your script loads, input is empty. Later, in the function the script is trying to add 6 to NaN, which will give you NaN.
This should work:
<script>
var output = document.getElementById("output");
var input = document.getElementById("input");
function addnum(N) {
var int_input = parseInt(input.value);
int_input = int_input + N;
output.innerHTML = int_input;
}
// Your eventListener function can be placed here
</script>
This works in console
var input = "12";
var int_input = parseInt(input);
function addnum(N) {
int_input = int_input + N;
console.log(int_input);
}
addnum(6);
do a console.log() with the input, to see what value it has.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.