In my code I have an if statement, using an isNaN()
. It is checking the input on a number field. If the input isNaN()
(is not a number) it should throw and alert()
Right now it’s throwing that alert no matter what is input. Could you help? Thanks. Here’s my code:
const increaseValue = document.getElementById('positive');
const enter = document.getElementById('enter-value');
// input reception code
function useInput(){
enter.addEventListener('click', function(){
if(isNaN(increaseValue)){
alert("Your input was not a number! Try again.");
}
})
}
useInput();
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="veiwport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="FinanceTool.css">
<title>Finance_Tool</title>
</head>
<body>
<main>
<input type="number" id="positive" class="input" placeholder="Input financial increase." min="0"/>
<button type="submit" id="enter-value">Enter</button>
</main>
<script src="FinanceTool.js"></script>
</body>
</html>
3
Answers
I figured it out. Thank you all for your help.
If you run
console.log(increaseValue)
, you’ll see thatincreaseValue
is an instance of an HTML element. If you need to check if the input’s value is a number, you should change the check to:Example:
The value of an
<input type="number">
is an empty string if the value isn’t a valid number, andisNaN('')
returnsfalse
.But the input also has a property
valueAsNumber
that returnsNaN
for invalid input: