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>
Advertisement
Answer
No, grade
refers to the textbox. You’re passing the value of the textbox into the checkGrade
function. The switch
statement is running over the grade
variable, which holds the value of the grade
textbox.
You can’t really “name” a switch statement. The argument to the switch
represents the value you are testing.
document
represents your HTML document, and value
is the value of the textbox named grade
. On another note, it is not recommended to use the onClick
attribute 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?