Checkboxes differ from text fields and textareas. Instead of having a value
as text fields and textareas do, they have a Boolean attribute called checked.
If a user has clicked a checkbox so that an × or check mark appears in
it, then checked equals true. If the checkbox is not on, then checked equals
false (remember—because true and false are Booleans, they don’t take
quotes).
Let me explain with an example:
<html>
<head>
<title>A Little Quiz</title>
<script type = "text/javascript">
<!-- hide me from older browsers
function scoreQuiz()
{
var correct = 0;
if (window.document.the_form.question1.checked == true) {
correct = correct + 1;
}
if (window.document.the_form.question2.checked == true) {
correct = correct + 1;
}
if (window.document.the_form.question3.checked == false) {
correct = correct + 1;
}
alert("You got " + correct + " answers right!");
}
// show me -->
</script>
</head>
<body>
<h1>A Little Quiz</h1>
Check the statements which are true:
<form name = "the_form">
<input type = "checkbox" name =
"question1"> All men are featherless bipeds<br>
<input type = "checkbox" name =
"question2"> All kangaroos are featherless bipeds<<br>
<input type = "checkbox" name = "question3"> All men are kangaroos<br>
<input type = "button" value = "score this quiz" onClick = "scoreQuiz();">
</form>
</body>
</html>
When a user clicks the button form element at the bottom of the window it calls the scoreQuiz() function. then creates a variable called correct and sets its value to 0. This variable keeps track of how many answers the visitor answered correctly.
The if-then statement in is slightly different from the other two. It says that if the checked property of the third checkbox is false (that is, the visitor
hasn’t selected the checkbox), then JavaScript should add 1 to correct.
To show visitors the correct answers after they click the score button we could use the scoreQuiz() function to determine the value of each checkbox by setting its checked property to true or false. updates the scoreQuiz() function to give the correct answers.
I add an else to each if-then clause, which sets the checkbox to the correct answer if the visitor gets the answer wrong. The first if-then clause, starting with , reads in plain English, “If the visitor checks the first checkbox, the answer is correct, so add 1 to the variable correct. Otherwise, check the first checkbox to indicate the correct answer.” If the visitor guessed wrong, selects the first checkbox by setting its checked property to true.
No comments:
Post a Comment