Building an Online Quiz
Before we discuss the script code, we first discuss the body element (lines 25–48) of the XHTML document. The body’s GUI components play an important role in the script.
Line 29 adds the tip image to the page. Lines 32–42 display the radio buttons and corresponding labels that display possible answer choices. Lines 44–45 add the submit and reset buttons to the page.
An XHTML form’s elements can be accessed individually using getElementById or through the elements property of the containing form object. The elements property
<?xml version = "1.0" encoding = "utf-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
<!-- Fig. 10.14: quiz.html -->
<html xmlns = "http://www.w3.org/1999/xhtml">
var myQuiz = document.getElementById( "myQuiz" );
// determine whether the answer is correct
if ( myQuiz.elements[ 1 ].checked )
alert( "Congratulations, your answer is correct" );
else // if the answer is incorrect
alert( "Your answer is incorrect. Please try again" );
} // end function checkAnswers
<form id = "myQuiz" onsubmit = "checkAnswers()" action = "">
<p>Select the name of the tip that goes with the
image shown:<br />
<img src="EPT.gif" alt="mystery tip"/>
<input type = "radio" name = "radiobutton" value = "CPE" />
<label>Common Programming Error</label>
<input type = "radio" name = "radiobutton" value = "EPT" />
<input type = "radio" name = "radiobutton" value = "PERF" />
<input type = "radio" name = "radiobutton" value = "PORT" />
<label>Portability Tip</label><br />
<input type = "submit" name = "submit" value = "Submit" />
<input type = "reset" name = "reset" value = "Reset" />
contains an array of all the form’s controls. The radio buttons are part of the XHTML form myQuiz, so we access the elements array in line 17 using dot notation (myQuiz.elements[ 1 ]). The array element myQuiz.elements[ 1 ] corresponds to the correct answer (i.e., the second radio button). Finally, line 17 determines whether the property checked of the second radio button is true. Property checked of a radio button is true when the radio button is selected, and it is false when the radio button is not selected. Recall that only one radio button may be selected at any given time. If property myQuiz.elements[ 1 ].checked is true, indicating that the correct answer is selected, the script alerts a congratulatory message. If property checked of the radio button is false, then the script alerts an alternate message (line 20).
Copyright © 2018-2020 BrainKart.com; All Rights Reserved. Developed by Therithal info, Chennai.