Reputation: 15
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>
Upvotes: -4
Views: 98
Reputation: 6840
The value of an <input type="number">
is an empty string if the value isn't a valid number, and isNaN('')
returns false
.
console.log(isNaN(''));
But the input also has a property valueAsNumber
that returns NaN
for invalid input:
const increaseValue = document.getElementById('positive');
const enter = document.getElementById('enter-value');
// input reception code
function useInput(){
enter.addEventListener('click', function(){
console.log(increaseValue.valueAsNumber);
console.log(increaseValue.value);
if(isNaN(increaseValue.valueAsNumber)){
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>
Upvotes: 1