for practice as a beginner I am trying to take a number from a text field, have the user press a button that adds 2 to that number, and then displays it through HTML. However, for some reason I keep getting NaN when applying the code below.
//Setup
var num1 = document.querySelector(".input-box").value;
var btn = document.querySelector(".btn");
//Add
var sum = parseInt(num1) + 2;
btn.addEventListener('click', (e) => {
e.preventDefault();
document.querySelector("#output").innerHTML = sum;
})
<html>
<head>
<title>Calculate</title>
<style>
</style>
</head>
<body>
<div class="sign">
<h1>Calculate</h1>
<form>
<input type="text" class="input-box" placeholder="Enter Number">
<input class="btn" type="button" value="Add 2">
</form>
<h1 id="output"></h1>
</div>
<script src="manip3.js"></script>
</body>
</html>
parseInt('') + 2isNaN. You merely calculatesumonce when the script gets loaded and not really on click.parseInt(value) !== NaNbefore adding 2.