PFS! Computer Science

Interacting with Web Pages
13.0. Overview

Today we'll be creating a "form" that will be used to administer a one question quiz.

We are going to be using some advanced JavaScript in this project, and you won't understand every detail of the code.

That's okay!

Just as you wrote your first "Hello, World!" program without quite knowing what you were doing, we're going to be using HTML (which you do understand a little), and JavaScript functions (which we have talked about), and i = i + 1; counters.

Let's get started!

13.1. Setting up your webpage

We've used the prompt function in JavaScript to give the user a chance to enter information into the computer so we can use it in our programs. Another common way to get information from the user is using a form on a webpage. Let's see how to do that.

A simple web form

Web forms can be used to have the user enter all sorts of information, from personal information on a dating site to credit card numbers for an online purchase. For our project, we just want the user to be able to read a multiple-choice questions, see the possible answers, select which answer they think is correct, and click a button to see if they were right.

Let's start with the index.html page. It's actually pretty short.

<!DOCTYPE html>
<html>

<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>replit</title>
  <link href="style.css" rel="stylesheet" type="text/css" />
</head>

<body> 

    <div id="quiz">
        <!-- the quiz questions will be placed here -->
    </div>
    <button id="submit">Submit Quiz</button>
    <div id="results">
        <!-- After the user submits their guesses, the 
             number of questions answered correctly will
             be displayed here.
        -->  
    </div>

    <!-- All the code to make this page come alive is contained
         in the JavaScript file!
    -->
    <script src="script.js"></script>

</body>

</html>

You probably recognize most of this as standard code that we start some of our projects with. There are three lines in the body of the document that set up three sections of the webpage that will be filled in later on by our JavaScript.

If you load this page now, nothing will happen. We still have to include our JavaScript that will fill in those missing sections of the webpage.

13.2. The script.js file

Now things get a little more serious. For the script.js file for your project, you'll need to put in this code:

// This function displays the quiz on the page
function buildQuiz()
{
    // variable to store the HTML output
    const output = [];

    // for each question...
    myQuestions.forEach(
    (currentQuestion, questionNumber) => 
    {
        // variable to store the list of possible answers
        const answers = [];
        // and for each available answer...
        for (letter in currentQuestion.answers)
        {
            // ...add an HTML radio button
            answers.push(
                `<label>
                <input type="radio" name="question${questionNumber}" value="${letter}">
                ${letter} :
                ${currentQuestion.answers[letter]}
              </label>`
            );
        }
        // add this question and its answers to the output
        output.push(
            `<div class="question"> ${currentQuestion.question} </div>
            <div class="answers"> ${answers.join('')} </div>`
        );
    }
    );

    // finally combine our output list into one string of HTML and put it on the page
    quizContainer.innerHTML = output.join('');
}
    



// This function reveals the results
function showResults()
{
    // gather answer containers from our quiz
    const answerContainers = quizContainer.querySelectorAll('.answers');

    // keep track of user's answers
    let numCorrect = 0;

    // for each question...
    myQuestions.forEach( (currentQuestion, questionNumber) => 
    {

        // find selected answer
        const answerContainer = answerContainers[questionNumber];
        const selector = `input[name=question${questionNumber}]:checked`;
        const userAnswer = (answerContainer.querySelector(selector) || {}).value;
        
        // if answer is correct
        if (userAnswer === currentQuestion.correctAnswer)
        {
            // add to the number of correct answers
            numCorrect++;
        
            // color the answers green
            answerContainers[questionNumber].style.color = 'lightgreen';
        }
        // if answer is wrong or blank
        else
        {
            // color the answers red
            answerContainers[questionNumber].style.color = 'red';
        }
    });

    // show number of correct answers out of total
    resultsContainer.innerHTML = `${numCorrect} out of ${myQuestions.length}`;  
}

// Set up references to the HTML document
const quizContainer = document.getElementById('quiz');
const resultsContainer = document.getElementById('results');
const submitButton = document.getElementById('submit');

// The questions are held in an array, and loaded by
// the function buildQuiz above
const myQuestions = [
  {
    question: "1. Who is the best teacher?",
    answers: {
      a: "Mr. White",
      b: "Ms. Campos",
      c: "Ms. Martinez"
    },
    correctAnswer: "c"
  }
]

// display quiz right away
buildQuiz();

// on submit, show results
submitButton.addEventListener('click', showResults);

Note that the single question for this multiple-choice quiz is contained near the bottom of the file, along with the value for the correct answer. You can modify this question if you like, or even add additional questions by including them in this section of the JavaScript file.

13.3. Fixing the styling

Our page looks kind of ugly right now: the font is blah, there aren't any colors, nor even a header at the top stating that this is a quiz.

Take a few moments to go into the style.css page and make some modifications there. Put an <h1> tag on the main page, too, so that people know they are taking a quiz.

13.4. Putting audio on a webpage

Your web browser—whether it's Chrome, Firefox, or Safari—supports HTML5, so adding audio to your project so that you can use it in your quiz is really easy.

Let's take this in a couple of steps.

Creating an audio question

Let's convert our simple text question to an audio question.

  1. Modify our quiz question so it looks like this:
    const myQuestions = [
      {
        question: "Who is the guitarist, singer, and songwriter for this song?",
        answers: {
          a: "Johnny B. Goode",
          b: "Miles Davis",
          c: "Chuck Berry"
        },
        correctAnswer: "c",
        audioFile: "assets/q1.mp3"
      }
    ]
    We've changed the text of the question, and we've also added an audioFile value at the end of the question
  2. Get a copy of this audio file onto your computer, and put it into an assets folder in your project.
  3. Finally, find the section with output.push in it and modify that section of code so that it looks like this:
    output.push(
        `<div class="question"> ${currentQuestion.question} </div>
        <p>Click to play song:</p>
        <p><audio controls>
        <source src="${currentQuestion.audioFile}" type="audio/mpeg">
        </audio></p>
        <div class="answers"> ${answers.join('')} </div>`
    );