Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why isn't my code adding a number with the input field (HTML/Javascript - Beginner)?

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>


    
like image 330
user3321460 Avatar asked Aug 24 '26 05:08

user3321460


1 Answers

You need to move the num1 and sum the inside the event listener

//Setup

var btn = document.querySelector(".btn");
//Add


btn.addEventListener('click', (e) => {
 e.preventDefault();
 // get the number
 var num1 = document.querySelector(".input-box").value;
 // add 2
 var sum = parseInt(num1) + 2;
 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>
like image 89
Marik Ishtar Avatar answered Aug 25 '26 18:08

Marik Ishtar