Question

Rookie developer, apologies for any unconventional code.

I'm working on a simple quiz. One question is displayed at a time with 3 possible answers on radio buttons. The answer "key" is stored in an array called allQuestions.

I'm looking for the correct way to compare if the user's answer (the selected radio button) is equal to the correct answer.

I’d prefer an explanation using JQuery but am not against a getElementByIdea solution. Heck, why not cover both!You'll see in the JS section that I attempt both.

Lastly, should I use a function in either of those approaches? Or is a stand-alone If/Then sufficient? You'll see I include one in the getElementByIdea attempt.

JSFiddle: http://jsfiddle.net/Ever/fYA5Y/

HTML

<body>
    <h2>JS and JQuery Quiz</h2>

    <div class="intro">
    Welcome! When the button at the bottom is clicked, the question and answers below will     
progress to the next question and respective answer chioces. Good luck!
    <br>
    </div>

    <br>

    <div class="questions">Ready?</div>

    <br>

    <input type="radio" id="radio1" name="radios"><label id="r1"> Yes</label></br>
    <input type="radio" id="radio2" name="radios"><label id="r2"> No</label></br>
    <input type="radio" id="radio3" name="radios"><label id="r3"> Wat </label></br>

    </br>

    <button>Submit</button>
</body>

CSS

div.intro{
font-weight: bold;
width: 50%;
}

div.questions{
text-align: left;
font-size: 25px;
width: 500px;
height: 100px;
border: 1px solid black;
padding: 5px;
}

JS

$(document).ready(function(){ 
//store quetsions, answer options, and answer key
var allQuestions = {
question: ["Who is Prime Minister of the United Kingdom?", "Which of the \
following is not a breed of dog?", "What sound does a pig make?", "When presented dessert menu,     
\
which item would Anne most likely order?"],
choices: [" David Cameron", " Gordon Brown", " Winston Churchill", " Retriever" , " Poodle", "  
Tabby", " Moo", " Oink", " Meow", "Salted Caramel Ice Cream", "Lime and Ginger Sorbet", "Double 
Chocolate Cake"],
answers: [1,1,1,1],
};

//global counters for each of the questions and answer choices
var q = 0;
var rb1= 0;
var rb2=1;
var rb3=2;
var ans=0;

//global counters to store the amount of correct and incorrect user answers
var userScore = {
correct: 0,
incorrect: 0, 
} 

//when button is clicked, update the quetstion to show the next question, and the
//radio buttons to show the next answer options.  
$('button').click(function(){
    //locate the current question and answer choices and set them to variables
    var currentQuestion = (allQuestions.question[q]);
    var currentRadio1 = (allQuestions.choices[rb1]);
    var currentRadio2 = (allQuestions.choices[rb2]);
    var currentRadio3 = (allQuestions.choices[rb3]);
    var currentAnswer = (allQuestions.answers[ans]);
    //update html to display the current question and answer choices
    $('.questions').html(currentQuestion);
    $('#r1').html(currentRadio1);
    $('#r2').html(currentRadio2);
    $('#r3').html(currentRadio3);
    //progress the question and answer choice counters
    q = q + 1;
    rb1 = rb1 + 3;
    rb2 = rb2 + 3;
    rb3 = rb3 + 3;
    ans = ans + 1;

    //Using JQuery, compare the user's answer (the selected radio button) to the correct  
            //answer. 
    //Do this by having the code look at all the radio buttons. If the checked one 
    //is equal to the correct answer, increment "correct" in <userScore>. 
    //If incorrect, increment "incorrect" in <userScore>.

    if $('input["radios"]:checked' == currentAnswer){
    userScore.correct++;
    }
    else{
    userScore.incorrect++;
    }

    //Alternative method: use getElementByID to do tally answers. 
    //function tallyAnswers() {
    //if (document.getElementById("radios").checked == currentAnswer) {
    //userScore.correct++;
    //}
    //else {
    //userScore.incorrect++;
    //}
    //}

    //when all questions have been done, alert the total correct and incorrect answers
    //alert(userScore.correct)  
    }); 
});



//Psuedocode:
//Use a JS object to separately hold each group of: questions, choices and correct answers.
//Use a JS function so that when <button> is clicked, it:
//**removes the current text from the <.questions> DIV
//**clears the radio buttons
//**adds the next question's text from <allQuestions> to the <.questions> DIV
//**adds the next anwers the radio buttons 
//Use a JS object to store each of the user's answers, which are determined by which
//radio button is selected when <button> is clicked. 
//If user clicks <button> without first selecting a radio button, do not update the form, and
//do not store their answer. Instead, alert the user.
//On the final page, let the user know they are done. Tally and display the total
//amount of correct answers. 
Était-ce utile?

La solution

http://jsfiddle.net/fYA5Y/1/

i've cleaned up your code, you have a good attempt, just wrong syntax

if ($('input[name="radios"]:checked').val() == currentAnswer){
userScore.correct++;
} else{
    userScore.incorrect++;
}
console.log(userScore);

as you can see, you should use $('input[name='xxxx']) to get elements by name, also you should set value to your input tags

<input type="radio" id="radio1" name="radios" value="1">

Autres conseils

i fixed the entire things, you did a good job but your logic design suffer in some aspect, but programming is a skills that sharpen during time, well done and continue

i stick to your design so just did some minor fixes. here is the link : the working one

these are the changes: - you have extra answer at start(yes,now,wat) that you didn't cater for that - when the user click on submit you are loading answer of next answer, so all the time one answer your code is ahead!

i assume your answer can be 0,1,2 (first radio button,second radio button...) also i defined two new variable, one is firstime that will take care of first question and lastanswer to take care of one question ahead

i get the answer by

answer=$('input[type=radio]:checked').next().html();

but you can get it in same way that monkeyinsight told in another answer, it depends on your design.

Labels for radio buttons should be outside their tag.

<label for="male">Male</label>
<input type="radio" id="male">

The for attribute chains the label to the correct radio button for easier selecting on mobile devices.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top