M.MFG M.MFG - 5 months ago 15
HTML Question

My console.log keeps saying NaN is false while it isn't

So I have this code and when the user types a number it should log "this is a valid number" in the console and else it should log "this is not a valid number". But my code keeps logging "this is a valid number". And I have to use isNaN.

Please be easy on me, I'm just starting JavaScript.

This is my HTML code:

<!doctype html>
<html>

<head>
<meta charset="UTF-8">
<title>Postcode</title>


<script src="postcode.js">
</script>
</head>

<body>

<form class="form">
<label for="postcode">Postcode: </label>
<input type="text" id="postcode">
</form>

</body>

</html>


And this is my JavaScript code:

window.addEventListener("load", init);

function init() {
alert("Content loaded");

var nameInput = document.getElementById('postcode');

document.querySelector('form.form').addEventListener('submit', function (e) {

//prevent the normal submission of the form
e.preventDefault();



if (nameInput === isNaN || nameInput === "") {
console.log("this is not a valid number!");}
else if (nameInput !== isNaN) {
console.log("this is a valid number!");}

});

}

Answer

Use isNaN(...) to check if a something is Not A Number:

isNaN('a'); // true

And also nameInput refers to a DOM node, get the value (or innerHTML):

isNaN(nameInput.value)

And your full code:

window.addEventListener("load", init);

function init() {
    var nameInput = document.getElementById('postcode');
    document.querySelector('.form').addEventListener('submit', function (e) {
        e.preventDefault();
        if (!nameInput.value || isNaN(nameInput.value)) {
            console.log("this is not a valid number!");}
        else {
            console.log("this is a valid number!");}
        }
    });
}
Comments