【问题标题】:Javascript Quiz - Get Selected Radio Button Value and Compare to Correct AnswerJavascript 测验 - 获取选定的单选按钮值并比较正确答案
【发布时间】:2019-07-05 06:07:30
【问题描述】:

我对 Web 开发很陌生,这是我的第一个项目。我正在尝试使用数组创建一个测验来显示问题、选择和答案。我已经成功地在网页上显示了问题和选择。但我仍然无法显示用户选择或获取选定的单选按钮。我必须这样做,这样我才能在这个测验中显示分数。

HTML:

<!DOCTYPE Html>
<html>
    <head>
    </head>

    <body>
        <div id="quiz"></div>
        <button id="button">Done!</button>
        <script src="scripts.js"></script>
    </body>
</html>

Javascript:

var myQuestions = [
['1. Which sentence uses "famish" correctly?', "After the straight exam, I 
felt too exhausted and famished to eat my favourite foods.", "I could eat a 
horse, I am famish now.", "I famished my stomach next time you treat me to a 
meal out.", "I will bring lots of pizza, that's a famish.", "a"],
["2. Priscila _______ rather not invest her savings in the stock market.", 
"must", "has to", "could", "would", "d"],
["3. Did you have any problem ______ our house?", "search", "to search", 
"searching", "for searching", "c"],

/*********************************************************************/

var quiz_id = document.getElementById('quiz');
var submitButton = document.getElementById("button");

/*********************************************************************/

myQuestions.forEach(function(myQuestions){

quiz_id.innerHTML += `
    <div>${myQuestions[0]} <br></div>
    <form>
        <label>
            <input class="answers" type="radio" name="choices" 
             value="a">${myQuestions[1]}<br/>
             <input class="answers" type="radio" name="choices" 
             value="b">${myQuestions[2]}<br/>
            <input class="answers" type="radio" name="choices" 
            value="c">${myQuestions[3]}<br/>
            <input class="answers" type="radio" name="choices" 
            value="d">${myQuestions[4]}<br/>
            </label>
    </form>
`;
});

/*********************************************************************/

function showResults(){

//1. set the total score
var total = 0;

//2. show the correct answer
myQuestions.forEach(function(myQuestions, index){
    var correctAnswer = myQuestions[5];
    quiz_id.innerHTML += `<div>correct answer for number ${index} : 
    ${correctAnswer}</div>`;
});

//3. show the user their answer
var choice = document.getElementsByName('choices');
var userChoice;
for(var i = 0; i < choice.length; i++){
    if(choice[i].checked){
        userChoice = choice[i].value;
    }
    quiz_id.innerHTML += `${userChoice}`;
}

//4. if the user choice matches the correct answer add a score to total 
variable
if(userChoice === correctAnswer){
    total++;
}
//5. display the scores
quiz_id.innerHTML = `<div>You have scored a total of ${total}</div>`;

}

/*********************************************************************/

submitButton.addEventListener("click", showResults);

在函数showResults()中

我在使用 3 号和 4 号时遇到了问题。

【问题讨论】:

    标签: javascript html arrays foreach radio-button


    【解决方案1】:

    我宁愿使用对象,而不是数组来存储你以后应该像数据库一样使用的数据(因为索引使事情变得更容易)

    希望代码对你有所帮助。

    var myQuestions = {
        q1: { // unique id for every question
            question: 'Which sentence uses "famish" correctly?',
            correctAnswer: 'After the straight exam, I felt too exhausted and famished to eat my favourite foods.',
            fakeAnswers: [
                'I could eat a horse, I am famish now.',
                'I famished my stomach next time you treat me to a meal out.',
                'I will bring lots of pizza, that\'s a famish.',
            ],
        },
        q2: {
            question: 'Priscila _______ rather not invest her savings in the stock market.',
            correctAnswer: 'would',
            fakeAnswers: ['must', 'has to', 'could'],
        },
        q3: {
            question: 'Did you have any problem ______ our house?',
            correctAnswer: 'searching',
            fakeAnswers: ['search', 'to search', 'for searching'],
        },
    };
    
    /*********************************************************************/
    
    var quiz_id = document.getElementById('quiz');
    var submitButton = document.getElementById('button');
    var userAnswers = {}; // store the selected answers in this object, indexed by question id
    
    /*********************************************************************/
    
    var aQuestion;
    Object.keys(myQuestions).forEach((questionId, arrayIndex) => {
        aQuestion = myQuestions[questionId];
        var questionContainer = document.createElement('div');
        var questionLabel = document.createElement('label');
        var optionContainer = document.createElement('section');
        var answers = [aQuestion.correctAnswer].concat(aQuestion.fakeAnswers);
    
        shuffleArray(answers);
        answers.forEach((answer) => {
            var radioButton = generateRadioButton(questionId, answer);
            optionContainer.appendChild(radioButton);
        });
    
        questionLabel.innerText = `${arrayIndex + 1}. ${aQuestion.question}\n`;
    
        questionContainer.appendChild(questionLabel);
        questionContainer.appendChild(optionContainer);
        quiz_id.appendChild(questionContainer);
    });
    
    /*********************************************************************/
    
    function showResults(params) {
        // Do your things
        console.log(userAnswers);
    
        // check a specific question (by question id)
        var qId = 'q2';
        if (userAnswers[qId] == myQuestions[qId].correctAnswer) {
            console.log(`The answer [${userAnswers[qId]}] is correct for the question: "${myQuestions[qId].question}"`);
        }
    }
    
    /*********************************************************************/
    
    submitButton.addEventListener('click', showResults);
    
    /*********************************************************************/
    
    function generateRadioButton(groupId, value) {
        var container = document.createElement('div');
        var label = document.createElement('label');
        var radioButton = document.createElement('input');
    
        radioButton.className = 'answers';
        radioButton.type = 'radio';
        radioButton.id = value;
        radioButton.value = value;
        radioButton.name = groupId;
        radioButton.addEventListener('input', (event) => {
            userAnswers[groupId] = event.currentTarget.value;
        });
    
        label.innerText = value;
        label.htmlFor = value;
    
        container.appendChild(radioButton);
        container.appendChild(label);
    
        return container;
    }
    
    function shuffleArray(array) {
        for (let i = array.length - 1; i > 0; i--) {
            const j = Math.floor(Math.random() * (i + 1));
            [array[i], array[j]] = [array[j], array[i]];
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2013-06-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-08-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多