Reputation: 23
How do I go about nesting an If/Else statement into a function and then calling that function using a user input in the body in order to make the function calculate the correct alert with JavaScript? I'm missing the knowledge of how to call the statement in the body it seems. Any help would be appreciated! :)
<!doctype html>
<html>
<head>
<title> JavaScript Playground </title>
<script type="text/javascript">
function grade(Grade){
if (Grade <= 90 && Grade >= 100) {
return alert("You made an A!");
} else {
return alert("I don't know what you made!");
}
}
</script>
</head>
<body>
<script>
var Grade = parseFloat(prompt("Please enter a number: "));</script>
</body>
</html>
Upvotes: 1
Views: 4541
Reputation: 177851
Several things
Your code could be written
function grade(){
var Grade = prompt("Please enter a number: ");
Grade = isNaN(Grade) || Grade.trim()==="" ? 0 : +Grade; // force number if "Not a Number" or an empty string
if (Grade >= 90 && Grade <= 100) {
alert("You made an A!");
} else {
alert("I don't know what you made!");
}
}
grade()
That said,
if (a) text = "a"; else if (b) text = "b"
construct<!doctype html>
<html>
<head>
<title> JavaScript Playground </title>
<script type="text/javascript">
// helper function to make a number from whatever is entered
const makeNum = str => isNaN(str) || str.trim() === "" ? 0 : +str; // convert to 0 if not a number
function grade(Grade) {
Grade = makeNum(Grade); // convert to number
return Grade >= 90 && Grade <= 100 ? "You made an A!" : "I don't know what you made!";
}
window.addEventListener("load",function() { // on page load
document.getElementById("gradeMe").addEventListener("click",function() {
document.getElementById("res").textContent = grade(document.getElementById('grade').value);
})
});
</script>
</head>
<body>
Please enter a number:
<input type="text" id="grade">
<input type="button" id="gradeMe" value="grade me" />
<span id="res"></span>
</body>
</html>
Upvotes: 2
Reputation: 1228
The line directly after
var Grade = parseFloat(prompt("Please enter a number: "));
You can call your function like grade(Grade);
The if/else is completely unrelated to how you call the function but I think the conditional inside your if statement is mixed up. I'm guessing you probably meant for it to be Grade >= 90 && Grade <= 100
rather than Grade <= 90 && Grade >= 100
.
Upvotes: 0