简体   繁体   中英

Javascript quiz won't recall previous answers

I'm new to programming and Javascript, and as a first project I'm trying to create a small quiz application.

I've included it here on jsfiddle: http://jsfiddle.net/ben220/L0y43q3d/

I've tried to design the program so that the user is able go back through the quiz and change any of their answers before they click to get their final score at the end. The user checks the radio button next to their chosen answer. When the user clicks 'next' to move on (or 'back' to revisit a previous question) their answer is passed to an array called 'choices', and this array will store all of the user's answers as they go through the quiz.

I've managed to write the program so that previous answers can be saved and recalled but there is one annoying problem. If the user checks a particular radio button more than once in the quiz, the program will only remember the first one. For example: if I am on Question 4 and check the radio button for Answer 2, I might decide to go back to the previous question and change my answer, before moving on. So I go back to Question 3 and change the answer to Answer 2. I have now chosen the same radio button on two consecutive questions. But now when I click 'next' to move onto Question 4 again I find that no radio button is checked, my answer was not saved.

I've really tried to fix this by myself but I do not understand what I've done wrong. If anyone out there could suggest a solution I'd be grateful. If any further clarification is needed let me know. Sorry if my explanation or my code is confusing - I'm still a newbie with Javascript! Many thanks.

<div id="container">
    <div id="quizArea">
        <h2 id="theQuestion">Question 1</h2>
        <fieldset id="myForm">
                <label><input type="radio" name="question" value="0" />Answer 1</label><br/>
                <label><input type="radio" name="question" value="1" />Answer 2</label><br/>
                <label><input type="radio" name="question" value="2" />Answer 3</label><br/>
                <label><input type="radio" name="question" value="3" />Answer 4</label><br/>
                <label><input type="radio" name="question" value="4" />Answer 5</label><br/>
        </fieldset>
        <div class="mini_container"><button id="next">Next</button></div>
        <button id="getScore">Get Score</button>
        <div class="mini_container"><button id="back">Back</button></div>
        <p id="submitError">Please choose an answer before proceeding to the next question</p>
        <div id="score"></div>
      </div>
 </div>

Javascript:

var module = (function () {

var theQuestions = [{question: "Question 1", choices: ["Answer 1", "Answer 2", "Answer 3", "Answer 4", "Answer 5"], answer: 2}, {question: "Question 2", choices: ["Answer 1", "Answer 2", "Answer 3", "Answer 4", "Answer 5"], answer: 4}, {question: "Question 3", choices: ["Answer 1", "Answer 2", "Answer 3", "Answer 4", "Answer 5"], answer: 1}, {question: "Question 4", choices: ["Answer 1", "Answer 2", "Answer 3", "Answer 4", "Answer 5"], answer: 1}, {question: "Question 5", choices: ["Answer 1", "Answer 2", "Answer 3", "Answer 4", "Answer 5"], answer: 3}],
score = 0,
title = document.getElementById("theQuestion"),
back = document.getElementById("back"),
next = document.getElementById("next"),
radioButtons = document.getElementById("options"),
options = document.getElementsByTagName("label"),
radios = document.getElementsByTagName("input"),
submitError = document.getElementById("submitError"),
scoreBtn = document.getElementById("getScore"),
scoreBox = document.getElementById("score"),
currentQ = 0;

var choices = [];

function getRadioInfo() {
var decision = null;
for(var i = 0; i < radios.length; i += 1) {
        if(radios[i].checked) {
            decision = radios[i].value;
        }
    }
return decision;
}

back.onclick = function() {
var decision = getRadioInfo();
choices[currentQ] = decision;
currentQ -= 1;
if(currentQ === 0) {
    back.style.display = "none";
}
if(currentQ < theQuestions.length) {
next.style.display = "block";
scoreBtn.style.display = "none";
}
title.innerHTML = theQuestions[currentQ].question;
var a = 0;
for(var i = 0; i < options.length; i += 1) {
    options[i].innerHTML = '<input type="radio" name="question" value="' + a + '" />' + theQuestions[currentQ].choices[a];
    a += 1;
}
restorePreviousAnswer();
};

var restorePreviousAnswer = function() {
for(var i = 0; i < choices.length; i += 1) {
    if(choices.indexOf(choices[i]) == currentQ) {
        var prev = choices[i];
    }
}
for(var x = 0; x < radios.length; x += 1) {
    if (radios[x].value == prev) {
        radios[x].checked = true;
    }
}
};


next.onclick = function() {
    var decision = getRadioInfo();
    if(decision == null) {
        submitError.style.display = "block";
        return;
    } else {
        submitError.style.display = "none";
    }
    choices[currentQ] = decision;
    currentQ += 1;
    if(currentQ > 0) {
        back.style.display = "block";
    }
    if(currentQ == theQuestions.length - 1) {
        next.style.display = "none";
        scoreBtn.style.display = "block";
    }
    title.innerHTML = theQuestions[currentQ].question;
    var a = 0;
    for(var i = 0; i < options.length; i += 1) {
        options[i].innerHTML = '<input type="radio" name="question" value="' + a + '" />' + theQuestions[currentQ].choices[a];
        a += 1;
    }
    restorePreviousAnswer();

};

scoreBtn.onclick = function() {
hideAll();
scoreBox.innerHTML = "You scored " + score + " out of " + theQuestions.length;
};

})();

I cleaned up your restorePreviousAnswer function to just if (choices[currentQ] != null) radios[choices[currentQ]].checked = true . Another part of the problem was that null values were being inserted in your array of answers when you went back before selecting a radio button.

jsFiddle example

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM