I refactored FizzBuzz using functions and everything is working great except for two if..else statements in the function meant to validate the user's input (validateValue). I want to alert users that empty strings, decimals and NaN are not allowed. The statement checking for decimals works, but not empty strings or NaN. When I enter an empty string or NaN, the prompt for no decimals appears. I want to fix this using vanilla JavaScript, no jQuery.
Here is the JavaScript:
function getValue(message) {
var msg = "Please enter a number from 1 to 100.";
if (message) {
msg = message;
}
return parseInt(prompt(msg));
}
function validateValue(num) {
if (num === "") {
return getValue("Please type something.");
} else if (num%1 !== 0) {
return getValue("No decimals allowed.");
} else if (isNaN(num)) {
return getValue("That is not a number!");
} else {
return num;
}
}
function fizzBuzz(num) {
for (var i = 1; i <= num; i++) {
if (i%15 === 0) {
document.getElementById("list").innerHTML += "FizzBuzz<br>";
}
else if (i%3 === 0) {
document.getElementById("list").innerHTML += "Fizz<br>";
}
else if (i%5 === 0) {
document.getElementById("list").innerHTML += "Buzz<br>";
}
else {
document.getElementById("list").innerHTML += i + "<br>";
}
}
}
var value = validateValue(getValue());
fizzBuzz(value);
Here is the HTML:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>FizzBuzz Refactor</title>
</head>
<body>
<div>
<p>Your FizzBuzz results:</p>
<ul id="list">
</ul>
</div>
<script type="text/javascript" src="app.js"></script>
</body>
</html>