How to change JavaScript Quiz to issue a pass and fail message instead of score

Viewed 111

I have created a simple quiz, as below:

var myQuestions = [
    {
        question: "Question1 would go here",
        answers: {
            a: 'Yes',
            b: 'No',
        },
        correctAnswer: 'b'
    },
    {
        question: "Question2 would go here",
        answers: {
            a: 'Yes',
            b: 'No',
        },
        correctAnswer: 'b'
    }
];

var quizContainer = document.getElementById('quiz');
var resultsContainer = document.getElementById('results');
var submitButton = document.getElementById('submit');

generateQuiz(myQuestions, quizContainer, resultsContainer, submitButton);

function generateQuiz(questions, quizContainer, resultsContainer, submitButton){

    function showQuestions(questions, quizContainer){
        // we'll need a place to store the output and the answer choices
        var output = [];
        var answers;

        // for each question...
        for(var i=0; i<questions.length; i++){
            
            // first reset the list of answers
            answers = [];

            // for each available answer...
            for(letter in questions[i].answers){

                // ...add an html radio button
                answers.push(
                    '<label>'
                        + '<input type="radio" name="question'+i+'" value="'+letter+'">'
                        + questions[i].answers[letter]
                    + '</label>'
                );
            }

            // add this question and its answers to the output
            output.push(
                '<div class="question">' + questions[i].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('');
    }


    function showResults(questions, quizContainer, resultsContainer){
        
        // gather answer containers from our quiz
        var answerContainers = quizContainer.querySelectorAll('.answers');
        
        // keep track of user's answers
        var userAnswer = '';
        var numCorrect = 0;
        
        // for each question...
        for(var i=0; i<questions.length; i++){

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

        // show number of correct answers out of total
        resultsContainer.innerHTML = numCorrect + ' out of ' + questions.length;
    }

    // show questions right away
    showQuestions(questions, quizContainer);
    
    // on submit, show results
    submitButton.onclick = function(){
        showResults(questions, quizContainer, resultsContainer);
    }

}
<div id="quiz"></div>
<button id="submit">Get Results</button>
<div id="results"></div>

However, I am trying to make it do 3 things:

  1. Instead of showing the score of the quiz, I want ONE Message to display for Pass and ONE message to display for Fail.

  2. I want it that if ALL questions are answered correctly, then it is a Pass, otherwise it is a Fail.

  3. I do not want the user to submit the quiz until ALL questions have an answer.

Any help with the above modifications would be greatly appreciated. thanks

1 Answers

Try this:

I am using the built-in required and onsubmit event of forms in html to make sure the user answered all questions.

If there is anything else you need done with this answer please send a comment.

var myQuestions = [
    {
        question: "Question1 would go here",
        answers: {
            a: 'Yes',
            b: 'No',
        },
        correctAnswer: 'b'
    },
    {
        question: "Question2 would go here",
        answers: {
            a: 'Yes',
            b: 'No',
        },
        correctAnswer: 'b'
    }
];

var quizContainer = document.getElementById('quiz');
var resultsContainer = document.getElementById('results');
var submitButton = document.getElementById('submit');

generateQuiz(myQuestions, quizContainer, resultsContainer, submitButton);

function generateQuiz(questions, quizContainer, resultsContainer, submitButton){

    function showQuestions(questions, quizContainer){
        // we'll need a place to store the output and the answer choices
        var output = [];
        var answers;

        // for each question...
        for(var i=0; i<questions.length; i++){
            
            // first reset the list of answers
            answers = [];

            // for each available answer...
            for(letter in questions[i].answers){

                // ...add an html radio button
                answers.push(
                    '<label>'
                        + '<input type="radio" name="question'+i+'" value="'+letter+'" required="true">'
                        + questions[i].answers[letter]
                    + '</label>'
                );
            }

            // add this question and its answers to the output
            output.push(
                '<div class="question">' + questions[i].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('');
        quizContainer.innerHTML += `<input id="submit" type="submit" value="Get Results">`;
    }


    function showResults(questions, quizContainer, resultsContainer){
    
        
        // gather answer containers from our quiz
        var answerContainers = quizContainer.querySelectorAll('.answers');
        
        // keep track of user's answers
        var userAnswer = '';
        var numCorrect = 0;
        
        // for each question...
        for(var i=0; i<questions.length; i++){

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

        // show number of correct answers out of total
        resultsContainer.innerHTML = numCorrect == myQuestions.length ? "Pass" : "Fail"
    }

    // show questions right away
    showQuestions(questions, quizContainer);
  document.querySelector("#quiz").addEventListener("submit", e => {
    showResults(questions, quizContainer, resultsContainer);
  });

}
<form id="quiz" action="javascript:void(0);">
<input id="submit" type="submit" value="Get Results">
</form>

<div id="results"></div>

Related