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 >
<form >
<label >Enter your first number:</label>
<input type="number" id="fnum" name="fnum">
</form>
<form >
<label >Enter your second number:</label>
<input type="number" id="snum" name="snum">
</form>
Javascript:
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 > </button>
CodePudding user response:
It is because document.querySelector(".fnum")
just return the <label >Enter your first number:</label>
element, not the <input type="number" id="fnum" name="fnum">
element, so it does not have .value
attribute,
therefore, document.querySelector(".fnum").value
return null.
To get the value of <input type="number" id="fnum" name="fnum">
, you can use document.getElementById("fnum").value
to do so.
For the <input type="number" id="snum" name="snum">
element, the problem is the same.
CodePudding user response:
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 >
<form >
<label >Enter your first number:</label>
<input type="number" id="fnum" name="fnum">
</form>
<form >
<label >Enter your second number:</label>
<input type="number" id="snum" name="snum">
</form>
<button > </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.