I'm trying to do a dynamic quiz in order to learn Javascript/jQuery/html and CSS. I got stuck because I just added a back button, with this back button the user can go back an see his last answer and also change it, if the last answer was correctly answered it does score--; but if is not answered correctly it doesn't reset any value, in order to avoid people to get infinite scores. My real problem is that I'm using a lastValue variable to store the last radio button checked so when you go back it can compare, but it just work well if you go back once, then lastValue doesn't update so the behaviour is weird. This is the piece of code I'm using to compare the values:
function backQuestion(){
if (number == 9){
$('#myForm').css('display', 'inline-block');
$('#question').css('display', 'block');
$('#next').css('display', 'inline-block');
$('#score').css('display', 'none');
}
if(number > 0){
number --;
addQuestionAndAnswers();
if (lastValue == allQuestions[number].answer){
score --;
console.log('your score after going back is: ' + score);
console.log('the last value is: ' + lastValue);
console.log('this is the value of number: ' + number);
}else{
//lastValue =
console.log('your score after going back is: ' + score);
console.log('the last value is: ' + lastValue);
console.log('this is the value of number: ' + number);
}
}
}
I also leave the the js fiddle demo so you can check the rest of the code and variables. While I was writing this I just thought about storing the values of the responses in an array and then just every response answered I can store that value in the array and then when you push the button back you can get that value in order to compare, then you can just delete that value if the answer is answered again. I'm not sure if this is a complicated way; I'll appreciate if someone can tell me or suggest me an easy way!
js fiddle: http://jsfiddle.net/xtatanx/Wn8Qg/2/
js fiddle result full screen: http://jsfiddle.net/xtatanx/Wn8Qg/2/embedded/result/
I would recommend storing all answers, like this:
http://jsfiddle.net/Wn8Qg/4/
$(ready);
function ready(){
var allQuestions =
[
{
question: "Whats my real name?",
choices: ["Jhonnatan", "Alberto", "Tatan","Jaime"],
answer: 0
},
{
question: "Who is Colombia's president?",
choices: ["Alvaro Uribe", "Andres Pastrana", "Juan Manuel Santos","Tatan"],
answer: 2
},
{
question: "My favorite super heroe?",
choices: ["Batman", "Flash", "Tatan","Javascript"],
answer: 3
},
{
question: "Wich sports do i practice?",
choices: ["Climbing", "Swimming", "Programming","Running"],
answer: 0
},
{
question: "Whats my dad's name?",
choices: ["Alberto", "Jorge", "Javier","Jose"],
answer: 1
},
{
question: "Whats my favorite color?",
choices: ["Red", "Purple", "Blue","All"],
answer: 2
},
{
question: "My favorite alcoholic drink",
choices: ["Vodka", "Aguardiente", "Rum","Tekila"],
answer: 3
},
{
question: "Whats my favorite kind of music?",
choices: ["Hardcore", "Reggaeton", "Salsa","Programming"],
answer: 0
},
{
question: "How many qestions has this quiz??",
choices: ["20", "8", "10","12"],
answer: 2
},
{
question: "My favorite programming lenguage?",
choices: ["Ruby", "Arduino", "Python","Javascript"],
answer: 3
}
];
var score = 0;
var number = 0;
var question = $('#question');
var choice1 = $('#answer0');
var choice2 = $('#answer1');
var choice3 = $('#answer2');
var choice4 = $('#answer3');
var next = $('#next');
var back = $('#back');
var currentQuestion = $('#current-question');
var answers = new Array(allQuestions.length);
next.click(on_click_next);
back.click(on_click_back);
populate();
function populate() {
currentQuestion.text(number + 1);
question.text(allQuestions[number].question);
choice1.text(allQuestions[number].choices[0]);
choice2.text(allQuestions[number].choices[1]);
choice3.text(allQuestions[number].choices[2]);
choice4.text(allQuestions[number].choices[3]);
$(":radio").prop('checked', false);
if (answers[number] !== null)
$(":radio").eq(answers[number]).prop('checked', true);
}
function on_click_next(){
if($(":radio:checked").length == 1)
{
answers[number] = $(":radio:checked").val();
number++;
if (number < allQuestions.length) {
populate();
} else {
displayResult();
}
}else{
alert('please select an answer before proceed');
}
function displayResult(){
var score = get_score();
currentQuestion.text(allQuestions.length);
$('#question, #alternatives').hide();
$('#next').hide();
$('#score').show();
$('#score').text('Your score is: ' + score + 'pts');
}
}
function get_score()
{
var result = 0;
for(var i = 0; i < answers.length; i++)
if (allQuestions[i].answer == answers[i])
result++;
return result;
}
function on_click_back()
{
if (number == allQuestions.length)
{
$('#question, #alternatives').show();
$('#next').show();
$('#score').hide();
number--;
populate();
}
else
{
if(number > 0)
{
number--;
populate();
}
}
}
}
Related
My code was working properly until I decided to make a small change, and I guess I accidentally deleted something because my console is saying hide image is not defined at decrement when I already defined hide image. I can't find my error everything worked fine :'(. I went over my hide image function and it seems like everything is correct. When I load it on html the error seems to appear when a user does not make a selection is runs the function decrement, so when time reaches zero it displays an image with the correct answer, and it used to clear it out and display the next question with the available choices, but now it just stays on the if time = 0 screen and doesn't move on to the next question.
$(document).ready(function () {
//set up object-array for questions
var trivia = [
{
question: "On Drake & Josh, what's Megan favorite phrase?'",
choices: ["Boobz", "Idiots", "Oh, really?", "Damn! Where are my
apples?"],
rightChoice: 0,
image: "assets/images/boobs.gif",
background: "<img src='assets/images/90back.jpg'>"
},
{
question: "What color lipstick does Spongebob use when he kisses
Mr. Krabs fake Millionth dollar?",
choices: ["Magenta", "Stardust", "Coral Blue #Oof", "Blorange"],
rightChoice: 2,
image: "assets/images/spongebob-coral-blue.gif",
background: "<img src='assets/images/90cart.jpg'>"
},
{
question: "What thottie accessory was popular in the 90's, that
is currently popular today?",
choices: ["chokers", "bandaids", "airpods", "tidepods"],
rightChoice: 0,
image: "assets/images/chokers.gif",
background: "<img src='assets/images/90back.jpg'>"
},
{
question: "During sleepovers, Mystery Date allowed girls to date
which sexy actor?",
choices: ["Port", "James Franco", "Paul Rudd", "Chris Evans, Mr.
America"],
rightChoice: 3,
image: "assets/images/chris-evans.gif",
background: "<img src='assets/images/90cart.jpg'>"
},
{
question: "What was the SPICIEST band in the 90's?",
choices: ["Madonna", "Hillary Clinton", "BackStreet Boyz", "The
Spice Girls"],
rightChoice: 3,
image: "assets/images/zig-a-zig-ha.gif",
background: "<img src='assets/images/90back.jpg'>"
}
];
var rightAnswer = 0;
var wrongAnswer = 0;
var unansweredCount = 0;
var time = 15;
var intervalId;
var userSelection = "";
var selected = false;
var running = false;
var totalCount = trivia.length;
var chosenOne;
var triviaRand;
var newArray = [];
var placeHolder = [];
//hide resetBtn until called
$("#resetBtn").hide();
//click startBtn button to start game
$("#startBtn").on("click", function () {
$(this).hide();
displayTrivia();
runTime();
for (var i = 0; i < trivia.length; i++) {
placeHolder.push(trivia[i]);
};
})
//time: run
function runTime() {
if (!running) {
intervalId = setInterval(decrement, 1000);
running = true;
}
}
//time--
function decrement() {
$("#timeLeft").html("<h4>π» Madonna, we're running out of time π» "
+ time + " π</h4>");
time--;
//stop time if reach 0
if (time === 0) {
unansweredCount++;
stop();
$("#choicesDiv").html("<p>Oh no! You ran out of time π. The
correct choice is: " + chosenOne.choices[chosenOne.rightChoice] + "
</p>");
hideimage();
}
}
//time stop
function stop() {
running = false;
clearInterval(intervalId);
}
play question and loop though and display possible answers
function displayTrivia() {
//generate random triviaRand in array
triviaRand = Math.floor(Math.random() * trivia.length);
//console.log(triviaRand);
chosenOne = trivia[triviaRand];
console.log(chosenOne);
$("#questionDiv").html("<h2>" + chosenOne.question + "</h2>");
for (var i = 0; i < chosenOne.choices.length; i++) {
var newUserChoice = $("<div>");
newUserChoice.addClass("answerChoices");
newUserChoice.html(chosenOne.choices[i]);
//assign array position to it so can check rightChoice
newUserChoice.attr("userChoices", i);
$("#choicesDiv").append(newUserChoice);
}
//click function to select rightChoice
$(".answerChoices").click(function () {
//parseInt() function parses a string argument and returns an
integer of the specified radix
//locate array based on userChoice
userSelection = parseInt($(this).attr("userChoices"));
console.log(userSelection);
if (userSelection === chosenOne.rightChoice) {
console.log(chosenOne.choices[chosenOne.rightChoice]);
stop();
selected = true;
rightAnswer++;
userSelection = "";
$("#choicesDiv").html("<p>Damn, boi π±βππ</p>");
hideimage();
console.log(rightAnswer);
} else {
stop();
selected = true;
wrongAnswer++;
userSelection = "";
$("#choicesDiv").html("<p>π€That is incorrect! The correct
choice is: " + chosenOne.choices[chosenOne.rightChoice] + "</p>");
hideimage();
console.log(wrongAnswer);
}
})
function hideimage() {
$("#choicesDiv").append("<img src=" + chosenOne.image + ">");
newArray.push(chosenOne);
trivia.splice(triviaRand, 1);
var hideimg = setTimeout(function () {
$("#choicesDiv").empty();
time = 15;
//run the score screen if all questions answered
if ((wrongAnswer + rightAnswer + unansweredCount) ===
totalCount) {
//clearbck();
$("#questionDiv").empty();
$("#questionDiv").html("<h3>π§ Game Over! Let's see
your score π±: </h3>");
$("#choicesDiv").append("<h4> π€ͺ Correct: " +
rightAnswer + "</h4>");
$("#choicesDiv").append("<h4> π€¬ Incorrect: " +
wrongAnswer + "</h4>");
$("#choicesDiv").append("<h4> π€― Unanswered: " +
unansweredCount + "</h4>");
$("#resetBtn").show();
rightAnswer = 0;
wrongAnswer = 0;
unansweredCount = 0;
} else {
runTime();
displayTrivia();
}
}, 2000);
}
$("#resetBtn").on("click", function () {
$(this).hide();
$("#choicesDiv").empty();
$("#questionDiv").empty();
for (var i = 0; i < placeHolder.length; i++) {
trivia.push(placeHolder[i]);
}
runTime();
displayTrivia();
})
}
})`
Just as a syntax error correction! You should use single or double quotation in src attribute of img tag in hideimage function:
$("#choicesDiv").append("<img src=' " + chosenOne.image + " '>");
I am creating a trivia game for a class and I am struggling to compare all of the values of a single index of a 2-dimensional array to a single value of a single index of another array. From my limited experience, I am using and if statement to compare these values. I must be missing a step but I am unsure how to solve it. The line of code for which I think the mistake lies is $(".choice").on('click', function() {});
Thank you for any help in advanced.
JS:
window.onload = function() {
$('#start').html('<div class="text-center"><button type="button" class="btn btn-default">Start</button></div>');
};
var questionArray = ["This bands second album went platinum 5 times in the UK and double Platinum in the US.", "This band was formed in Australia and their first album, which had you Walking On A Dream, has sold over 3 million copies."];
var optionArray = [["Radio Head", "Gorillaz", "Coldplay", "Arctic Monkeys"], ["Empire Of The Sun", "M83", "MGMT", "Two Door Cinema Club"]];
var answerArray= ["Gorillaz", "Empire Of The Sun"];
var imageArray= ["http://cdn3.pitchfork.com/artists/1767/m.65d9c64d.jpg", "http://crowningmusic.com/storage/rA7GUFFoBCtT8Jg4L1tv.png", "", "", ""];
var count = 0;
var question = 0;
$("#start").on('click', function() {
$(this).css("display","none");
timer(
30000,
function(timeleft) {
$('#timer').html(timeleft);
},
function() {
// What happens after //
}
);
$("#question").html(questionArray[question]);
for (var j = 0; j < 4; j++) {
$("#options").append('<button class="choice">' + optionArray[question][j] + "</button>" + "<br>");
}
$(".choice").on('click', function() {
console.log('click');
console.log(answerArray[question])
if (optionArray[question] == answerArray[question]) {
console.log("Working");
}
});
// $("#holder").html("<img src=" + questionArray[count] + ">");
});
function nextQuestion() {
count++;
}
// Timer Function //
function timer(time,update,complete) {
var start = new Date().getTime();
var interval = setInterval(function() {
var now = time-(new Date().getTime()-start);
if( now <= 0) {
clearInterval(interval);
complete();
}
else update(Math.floor(now/1000));
},100); // the smaller this number, the more accurate the timer will be
}
When you are comparing the answers to the question with the correct answer, you need to include the index of the user selected choice. Try something like this:
$("#question").html(questionArray[question]);
for (var j = 0; j < 4; j++) {
// Include an ID in the choice button
$("#options").append('<button class="choice" id="choice_' + j + '">' + optionArray[question][j] + "</button>" + "<br>");
}
$(".choice").on('click', function() {
console.log('click');
console.log(answerArray[question]);
// Get the index of the selected answer through the ID attribute
var selectedAnswerIndex = $(this).attr('id').substring("choice_".length);
if (optionArray[question][selectedAnswerIndex] === answerArray[question]) {
console.log("Working");
}
});
Another options that doesn't deal with answer index might look like this:
$(".choice").on('click', function() {
console.log('click');
console.log(answerArray[question])
// Use the text content of the button to check the answer
if ($(this).text() === answerArray[question]) {
console.log("Working");
}
});
Note: This relies on the fact that the button only contains the possible answer value between the tags. If you put anything else inside the button, this solution would not work.
I am creating a basic Trivia Game for a Web Dev class. We are to use HTML/CSS/JS/jQuery to create it. The new element that we are to work with in this assignment are the setTimeout() & setInterval() methods.
After clicking the start button, the game will ask a question and offer 4 possible answers. The user either clicks an answer or the timer runs out. The results are displayed and then then the next questions auto-loads. Once all of the questions in the questions array are asked, the game displays the overall results and then refreshes screen.
The bug that I discovered is that if I let the timer run all the way down until the "zero" is just displayed on the screen and then quickly click on an answer, it causes the game to react as if the conditions of an answer being clicked and the time running out had occurred simultaneously. Then the next question loads too many answers and the timer is decrementing at an increased rate. I'm not sure if there is some sort of time lag in the timer reaching zero somewhere that allows the answer clicks to transmit through and this creates a new timerID that doesn't get cleared which causes the time decrementing on the next question to increase in rate.
I've created a Fiddle for this: https://jsfiddle.net/brianpatrickhummel/0a2hg782/
var correctAnswers = 0;
var incorrectAnswers = 0;
var unansweredQuestions = 0;
var timeRemaining = 16;
var intervalID;
var indexQandA = 0; //index to load a different question each round without the game reset or screen refresh
var answered = false; //variable to stop the timer if user has clicked an answer
var correct;
var triviaGame = [
{question:"HOW MANY COLORS ARE THERE ON A RUBIK'S CUBE ?", answer:["5", "6", "7", "4"], correct: "1", image:("assets/images/rubik.png")},
{question:"WHAT IS THE SPEED OF LIGHT ?", answer:["8,600 MILES per SECOND","86,000 MILES per SECOND","186,000 MILES per SECOND","886,000 MILES per SECOND"], correct:"2", image:("assets//images/lightspeed.jpg")},
{question:"APPROXIMATELY HOW LONG DOES IT TAKE FOR SUNLIGHT TO REACH THE EARTH ?", answer:["45 SECONDS", "10 HOURS", "2 HOURS 15 MINUTES", "8 MINUTES"], correct:"3", image:("assets//images/sunlight.jpg")},
{question:"WHAT ELEMENT'S CHEMICAL SYMBOL IS Pb ?", answer:["POTASSIUM","STRONTIUM","LEAD","PALLADIUM"], correct:"2", image:("assets//images/periodictable.png")},
{question:"HOW FAST CAN BEES FLY ?", answer:["35 MPH", "15 MPH", "48 MPH", "8 MPH"], correct:"1", image: ("assets/images/bee.png")},
{question:"WHAT IS THE MOST ABUNDANT ELEMENT IN THE UNIVERSE ?", answer:["HYDROGEN", "OXYGEN", "HELIUM", "CARBON"], correct:"0", image:("assets//images/universe.png")},
{question:"THE AIR THAT WE BREATHE IS COMPRISED MOSTLY OF WHAT ELEMENT ?", answer:["CARBON", "ARGON", "OXYGEN", "NITROGEN"], correct:"3", image:("assets//images/breathe.jpg")},
{question:"WHAT IS THE DIAMETER OF THE EARTH ?", answer:["140,000 MILES", "2,500,000 MILES", "8,000 MILES", "25,000,000 MILES"], correct:"2", image:("assets//images/earth.png")}
];
// ------------- FUNCTION DECLARATIONS ----------------------------
function startGame() {
console.log("game has begun");
$('.start-button').remove();
correctAnswers = 0;
incorrectAnswers = 0;
unansweredQuestions = 0;
loadQandA ();
}
function loadQandA() {
// console.log(correctAnswers);
// console.log(incorrectAnswers);
// console.log(unansweredQuestions);
// console.log(indexQandA);
answered = false; // will allow timeRemaining to be pushed back to <h5> after round reset....else statement in function timer()
timeRemaining = 16;
intervalID = setInterval(timer, 1000);
if (answered === false){
timer();
}
correct = triviaGame[indexQandA].correct;
var question = triviaGame[indexQandA].question;
$('.question').html(question);
for (var i = 0; i < 4; i++) {
var answer = triviaGame[indexQandA].answer[i];
$('.answers').append('<h4 class= answersAll id=' + i + '>' + answer + '</h4>');
}
$( "h4" ).click(function() {
var id = $(this).attr('id');
// alert(id);
if (id === correct) {
answered = true; // stops the timer
// alert("correct answer");
$('.question').text("THE ANSWER IS: " + triviaGame[indexQandA].answer[correct]);
correctAnswer ();
}
else {
answered = true; //stops the timer
// alert("incorrect answer");
$('.question').text("YOU CHOSE: " + triviaGame[indexQandA].answer[id] + ".....HOWEVER THE ANSWER IS: " + triviaGame[indexQandA].answer[correct]);
incorrectAnswer();
}
});
}
function timer() {
if (timeRemaining === 0) {
answered = true;
clearInterval(intervalID);
$('.question').text("THE CORRECT ANSWER IS: " + triviaGame[indexQandA].answer[correct]);
unAnswered();
}
else if (answered === true) {
clearInterval(intervalID);
}
else {
timeRemaining--;
$('.timeRemaining').text('YOU HAVE ' + timeRemaining + ' SECONDS TO CHOOSE').removeClass('animated pulse infinite');
}
}
function correctAnswer() {
correctAnswers++;
$('.timeRemaining').text("YOU HAVE ANSWERED CORRECTLY!").css({'color':'#3D414F'}).addClass('animated pulse infinite');
resetRound();
}
function incorrectAnswer() {
incorrectAnswers++;
$('.timeRemaining').text("YOU HAVE ANSWERED INCORRECTLY!").css({'color':'#3D414F'}).addClass('animated pulse infinite');
resetRound();
}
function unAnswered() {
unansweredQuestions++;
$('.timeRemaining').text("YOU FAILED TO CHOOSE AN ANSWER").css({'color':'#3D414F'}).addClass('animated pulse infinite');
resetRound();
}
function resetRound() {
$('.answersAll').remove();
$('.answers').append('<img class=answerImage src="' + triviaGame[indexQandA].image + ' ">'); // adds answer image
indexQandA++; // increments index which will load next question when loadQandA() is called again
if (indexQandA < triviaGame.length) {
setTimeout(function(){ loadQandA(); $('.answerImage').remove();}, 5000); // removes answer image from previous round
}
else {
setTimeout(function(){
$('.question').remove();
$('.timeRemaining').remove();
$('.answerImage').remove();
$('.answers').append('<h4 class= answersAll end>CORRECT ANSWERS: ' + correctAnswers + '</h4>');
$('.answers').append('<h4 class= answersAll end>INCORRECT ANSWERS: ' + incorrectAnswers + '</h4>');
$('.answers').append('<h4 class= answersAll end>UNANSWERED QUESTIONS: ' + unansweredQuestions + '</h4>');
setTimeout(function(){ location.reload(); }, 7000);
}, 5000);
}
}
// ----------------------- MAIN PROCESS ---------------------
$('.startButton').on("click", function() {
$('.startButton').removeClass('infinite').addClass('animated fadeOutDown'); //manages the Animate.css applied to Start Button
startGame();
});
Each time you establish a timer with either setTimeout or setInterval, you need to set a variable to the returned timer id. That variable needs to have a high enough scope so that you can access it from any place where the timer must be interacted with.
Then, anywhere you need to interrupt the timer, you can clear it. In your case, when an answer is clicked, you need to stop the countdown timer.
Here's a scaled down example:
window.addEventListener("DOMContentLoaded", function(){
var clock = document.getElementById("clock");
var btnStart = document.getElementById("btnStart");
var btnStop = document.getElementById("btnStop");
// Declare this where you can get at it
var timer1 = null;
function start(){
clock.textContent = new Date().toLocaleTimeString();
timer1 = setTimeout(start, 900);
}
function stop(){
// Cancel the timer
clearTimeout(timer1);
}
btnStart.addEventListener("click", start);
btnStop.addEventListener("click", stop);
start();
});
<div id="clock"></div>
<button id="btnStop">Stop the Clock</button>
<button id="btnStart">Start the Clock</button>
So I have this quiz I've been building at https://jsfiddle.net/juligan01/ko5jqhov/. I was able to figure out how to keep the radio button choices when you click the back button, but I can't figure out how to keep them when you click the next button. There has to be an easier way than what I'm doing. Can someone help? Here is the JavaScript:
var correct = 0; //count of correct answers
var incorrect = 0; //count of incorrect answers
var questionCount = 0; //count of questions
var answers = [];
var choice;
var allQuestions = [{
question: "What is Elvis Presley's middle name?",
choices: ["David", "Aaron", "Eric", "Jack"],
correctAnswer: 1
}, {
question: "Who is the singer of the Counting Crows?",
choices: ["Adam Duritz", "John Adams", "Eric Johnson", "Jack Black"],
correctAnswer: 0
}, {
question: "Who is the Queen of Soul?",
choices: ["Mariah Carey", "Whitney Houston", "Aretha Franklin", "Beyonce"],
correctAnswer: 2
}, {
question: "Which famous group was once known as The Quarrymen?",
choices: ["The Beatles", "The Birds", "The Who", "Led Zeppelin"],
correctAnswer: 0
}];
var totalQuestions = allQuestions.length; //total number of questions
function loadQuestion(questionCount, choice) { //load the next question
if (questionCount == totalQuestions) { //if you've answered all questions
$("#next").hide();
$("#back").hide();
$("#score").hide().append(correct + "/" + totalQuestions + " correct!").fadeIn("slow");
$("#restart").show();
$("#restart").click(function() {
location.reload(); //reload page when #restart is clicked
});
} else {
$("#next").show();
$("#restart").hide();
$("#quiz").hide().fadeIn("slow");
$("#quiz").append(allQuestions[questionCount].question + "<br><br>");
for (var i = 0; i < allQuestions[questionCount].choices.length; i++) {
if (i == choice) {
$("#quiz").append("<input type='radio' name='questionChoices' value='" + i + "'checked>" + allQuestions[questionCount].choices[i] + "<br>");
} else {
$("#quiz").append("<input type='radio' name='questionChoices' value='" + i + "'>" + allQuestions[questionCount].choices[i] + "<br>");
}
}
}
}
$("#next").click(function() { //on click of next button
if (!$("input").is(":checked")) { //if nothing is checked
alert("Please make a selection.");
} else {
if ($("input:radio[name=questionChoices]:checked").val() == allQuestions[questionCount].correctAnswer) { //if radio button is correct
correct++; //increase correct number
$("#symbols").hide().append("<span style='color: green'>β</span>").fadeIn("slow");
} else {
incorrect++; //increase incorrect number
$("#symbols").hide().append("<span style='color: red'>X</span>").fadeIn("slow");
}
answers.push($("input:radio[name=questionChoices]:checked").val());
questionCount++; //increase questionCount
$("#quiz").empty(); //empty #quiz div
loadQuestion(questionCount); //run loadQuestion again
}
});
$("#back").click(function() { //on click of back button
if (questionCount > 0) {
$("#symbols").children().last().remove(); //remove last span item
questionCount--; //decrease questionCount
choice = answers[answers.length - 1];
answers.pop();
$("#quiz").empty(); //empty #quiz div
loadQuestion(questionCount, choice); //run loadQuestion again
}
});
loadQuestion(questionCount); //initialize the function
Here's a working solution, although I noticed a bug that made the final result display the answers out of 5 (e.g. 3/5) but I couldn't reproduce the bug after several tries, be aware though.
Using .pop() on back button removed any information you collected on the next button, so I got rid of that so you keep the information. Changed the way information in the array was created so it's based on the question number not the array length. Made the choice be loaded on the forward button or you would never see a choice, it's undefined if there's no choice to display.
https://jsfiddle.net/ko5jqhov/62/embedded/result/
$("#next").click(function() { //on click of next button
if (!$("input").is(":checked")) { //if nothing is checked
alert("Please make a selection.");
} else {
if ($("input:radio[name=questionChoices]:checked").val() == allQuestions[questionCount].correctAnswer) { //if radio button is correct
correct++; //increase correct number
$("#symbols").hide().append("<span style='color: green'>β</span>").fadeIn("slow");
} else {
incorrect++; //increase incorrect number
$("#symbols").hide().append("<span style='color: red'>X</span>").fadeIn("slow");
}
alert(answers[questionCount+1]);
answers[questionCount] = ($("input:radio[name=questionChoices]:checked").val());
choice = answers[questionCount+1];
questionCount++; //increase questionCount
$("#quiz").empty(); //empty #quiz div
loadQuestion(questionCount, choice); //run loadQuestion again
}
});
$("#back").click(function() { //on click of back button
if (questionCount > 0) {
$("#symbols").children().last().remove(); //remove last span item
questionCount--; //decrease questionCount
choice = answers[questionCount];
//answers.pop();
$("#quiz").empty(); //empty #quiz div
loadQuestion(questionCount, choice); //run loadQuestion again
}
});
I am trying to create the proverbial quiz in Javascript as my first 'from scratch' exercise. This is my fiddle, which has all the other code.
This is my question:
var allQuestions = [{
"question": "Who was Luke's gunner in the battle at Hoth?",
"choices": ["Dak", "Biggs", "Wedge", "fx-7"],
"correctAnswer": 0
}];
Here in this function, I included the loop which should go over the radio buttons vs. the users selection. See below.
function answerFwd() {
var answerOutput = " ";
var itemAnswers = allQuestions;
var answer = 0;
var playerTally = 0;
var playerFeedback = "";
var playerMessage = document.getElementById("playerMessage");
Right now I am stuck with this;
Matching the correct answer in the array, with what a user would select in the radio buttons and then dynamically displaying a score.
Right now, I can get the 0 to display, but no increment.
var radioValue = $("input[type='radio'].radioButtons:checked").val();
if (currentAnswer <= itemAnswers.length) {
currentAnswer++;
}
createRadioButtonFromArray(itemAnswers[currentQuestion].choices);
for(i = 0; i < radioValue.length; i++) {
if(radioValue[i].checked) {
if(radioValue[i].value == itemAnswers.correctAnswer) {
playerTally++;
break;
}
}
}
playerFeedback += "<h4>" + playerTally + "</h4> <br/>";
playerMessage.innerHTML = playerFeedback;
}
I am not opposed to a solution with jQuery, but would prefer a vanilla JS alternative, just so I can really see what is going on!
Thank you all in advance!
Before you progress to the next question, you can figure out if an answer is correct with
if (document.querySelectorAll("#responses input")[allQuestions[currentQuestion].correctAnswer].checked)
The complete solution is
fiddle
var radios = document.querySelectorAll("#responses input");
var correct = allQuestions[currentAnswer].correctAnswer;
if (radios[correct].checked) {
playerTally++;
playerFeedback += "<h5>" + playerTally + "</h5> <br/>";
playerMessage.innerHTML = playerFeedback;
}
if (currentAnswer <= itemAnswers.length) {
currentAnswer++;
}
And now I look closely it is the same as Mr. Me's