I am having troubles understanding the xhtml syntax for calling a function with an input button. I have searched for this, but cannot find a clear explanation.
This snippet of code is from my book, and it works ok, but I’m not sure exactly how the following line works:
onclick="checkGrade(document.gradeForm.grade.value);"
From what I can figure out, gradeForm is the form, and then grade is the switch statement? So would you use Foo if you had another switch statement called foo inside the checkGrades function? And I am not sure what document or value are for inside the onClick checkGrade function.
Any help would be very much appreciated!
<script type="text/javascript">
function checkGrade(grade) {
switch (grade.toUpperCase()) {
case "A":
window.alert("Your grade is excellent.")
break;
case "B":
window.alert("Your grade is good.")
break;
case "C":
window.alert("Your grade is fair.")
break;
case "D":
window.alert("You are barely passing.")
break;
case "F":
window.alert("You failed.")
break;
default:
window.alert("You did not enter a valid letter grade.");
break;
}
}
</script>
<p>Please enter your grade below:</p>
<form action="#" name="gradeForm">
<input type="text" name="grade" />
<input type="button" value="Check Grade" onclick="checkGrade(document.gradeForm.grade.value);" />
</form>
No,
graderefers to the textbox. You’re passing the value of the textbox into thecheckGradefunction. Theswitchstatement is running over thegradevariable, which holds the value of thegradetextbox.You can’t really “name” a switch statement. The argument to the
switchrepresents the value you are testing.documentrepresents your HTML document, andvalueis the value of the textbox namedgrade. On another note, it is not recommended to use theonClickattribute in XHTML/HTML. Unobtrusive Javascript is preferred, where you bind a handler to the button. For more details, I recommend reading up on the Document Object Model, specifically The DOM and Javascript.How old is this book you’re using?