In this lab you will write your own functions to grade an online quiz and validate required inputs for a form. The HTML file that contains the form with the quiz is given to you. This file links to a JavaScript file, code.js, which you can download here. Notice that code.js is only a template, which we will fill in today. We will write JavaScript code that:

  1. Calculates and reports a score for the quiz, based on the correct answers and the user's input. This happens when the user clicks on the "Check answers" button.
  2. When the user clicks on "Submit", the form is validated. If it passes validation then an email is sent to your account, with the form's contents. In the opposite case, submission is blocked.
  3. When the reset button is clicked, the form's fields are set back to their initial state.

Task 1

Task 2: Grade the Quiz

In code.js, define the gradeQuiz() function that grades the quiz.

The area to the right of the button is called quiz_result (quiz_result is the ID of that area of the page). Here is the code that creates quiz_result alongside the form itself:


 <input type ="button" 
           value ="Check answers" 
           onClick = "gradeQuiz();">
 <span id="quiz_result" class = "message">   
 </span>

The score of the quiz will be shown next to the button, like this:

One answer correct
Two answers correct
All three answers correct
The correct answers will be given to you in class. As an example, here is how you can check the correctness of the check-box question:
           
//grade the (check-box) third question
if ((document.quizForm.q3[1].checked) && (document.quizForm.q3[2].checked) && 
(!document.quizForm.q3[0].checked)) {
   tally = tally + 1;
}
                
The function presents the result on the page, by setting the innerHTML property of the quiz_result span, like:
         
document.getElementById("quiz_result").innerHTML = " Perfect Score!"; 
           
           

gradeQuiz() is called when the user clicks on .

Task 3: Reset the form

In code.js, define a resetForm() function that resets each question in the form to its initial state (i.e., red asterisks and initial message restored).

     
document.getElementById("name_asterisk").style.visibility="visible";
document.getElementById("quiz_result").innerHTML = "";

The event handler for the Reset button calls this function.

Task 4: Validate the Form

In code.js, define a validForm() function that validates the two required inputs: the user's name and whether they have taken a CS course. When the user clicks on the Submit button, validForm() is called. Our validation will be modular: We will define separate helper functions to validate each type of question. The validForm() function will just call the helper functions.

The following defines a valid input: