Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

JavaScript: getting 'NaN' from an input value

First time trying JavaScript, and for now I just want to make sure the site recognises the value that I’m inputting by having the console print it back at me. For some reason, I keep getting NaN as the result, and I can’t figure out why.

HTML:

<div class="container">
        <form class="question-1">
            <label class="fnum">Enter your first number:</label>
            <input type="number" id="fnum" name="fnum">
        </form>

        <form class="question-2">
            <label class="snum">Enter your second number:</label>
            <input type="number" id="snum" name="snum">
        </form>

Javascript:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

const buttonAdd = document.querySelector(".plus");

buttonAdd.addEventListener("click", (e) =>{
   var num1 = parseFloat(document.querySelector(".fnum").value);
   var num2 = parseFloat(document.querySelector(".snum").value);
   console.log(num1);
   console.log(num2);
});

html includes: <button class="plus">+</button>

>Solution :

const buttonAdd = document.querySelector(".plus");

buttonAdd.addEventListener("click", (e) =>{
   var num1 = parseFloat(document.querySelector("#fnum").value);
   var num2 = parseFloat(document.querySelector("#snum").value);
   console.log(num1);
   console.log(num2);
});
<div class="container">
        <form class="question-1">
            <label class="fnum">Enter your first number:</label>
            <input type="number" id="fnum" name="fnum">
        </form>

        <form class="question-2">
            <label class="snum">Enter your second number:</label>
            <input type="number" id="snum" name="snum">
        </form>
        <button class="plus">+</button>
</div>

Your query selector is wrong.

document.querySelector(".fnum")

This is for what class name is fnum.

document.querySelector("#fnum")

Should be like the above for id.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading