Why does browser show me only one alert box - javascript

Down here you can see my code i have problem that only show me 1 alert box even i put index++. What is solution of my problem.
MY CODE
var questions = [
{
text: "Da li je javascript dobar jezik",
correctAnswer : true
},
{
text: "Da li je css programski jezik",
correctAnswer : true
},
{
text: "Da li je php programski jezik",
correctAnswer: true
}
]
var index = 0;
var score = 0;
function quiz(){
var quizQuestion = confirm(questions[index].text);
if (quizQuestion === questions[index].correctAnswer){
score++;
}
index++;
if (index == questions[index]){
index=0;
}
}
quiz();
I exepted to show me 3 alert boxes but only show me one

If you want to keep going through the questions, call quiz again at the end of the function if the last index has not been reached.
function quiz() {
// ...
if (index < questions.length) quiz();
}
var questions = [{
text: "Da li je javascript dobar jezik",
correctAnswer: true
},
{
text: "Da li je css programski jezik",
correctAnswer: true
},
{
text: "Da li je php programski jezik",
correctAnswer: true
}
]
var index = 0;
var score = 0;
function quiz() {
var quizQuestion = confirm(questions[index].text);
if (quizQuestion === questions[index].correctAnswer) {
score++;
}
index++;
if (index < questions.length) quiz();
}
quiz();
console.log('Score', score);

Related

Why is my function to hide image not working properly?

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 + " '>");

Jquery/Javascript: Countdown Timer acting erratically

I am trying to make a simple quiz using javascript with timed questions. Each question lasts for 10 seconds before moving on to the next. The countdown timer does well for the first question, after which it starts to speed up or display random numbers for following questions. Here is my code,
P.S. I apologize for the inefficient and hectic code, I'm still new to javascript and I will make the code more streamlined once I fix this issue.
var questionList = [
{
q:"What is a dog?",
a:["fish","mammal","plant","prokaryote"],
answer: 1
},
{
q:"What is a cat?",
a:["mammal","fish","plant","amphibian"],
answer: 0
},
{
q:"What is a tree?",
a:["plant","fish","mammal","none"],
answer: 0
},
{
q:"What do cars run on?",
a:["gasoline","water","ethanol","liquid oxygen"],
answer: 0
},
{
q:"What is 4 x 4?",
a:["8","16","4","160"],
answer: 1
},
{
q:"What is the capital of Australia?",
a:["Brisbane","GoldCoast","Perth","Canberra","Melbourne"],
answer: 3
},
{
q:"What is the national flower of Canada?",
a:["sunflower","daisy","trillium","rose","lotus"],
answer: 2
}
];
//--------------------------------------
var picked;
var qcount = 0;
var output = [];
var timer;
var timer2;
var timeLeft = 10;
var correctQ = 0;
var wrongQ = 0;
//var randomQ = Math.floor(Math.random()*7);
var x = questionList[qcount];
var j = x.answer;
// var cAns = x.a[j];
//console.log(cAns);
console.log(j);
//new Q w/ options
function qGen(){
timer = setInterval(time, 1000)
$('#question').text(x.q);
for (var i=0; i < (x.a).length; i++){
var newLi = $('<button>');
newLi.attr('data-id', i);
newLi.addClass("answer").text(x.a[i]);
$('#list').append(newLi);
}
}
qGen();
// correct answer
function clickChoice(){
$('#list').on("click",'button', function(){
picked = parseInt($(this).attr("data-id"));
console.log(picked + " click");
if (picked === j){
console.log(j + " if");
qcount++;
x = questionList[qcount];
j = x.answer;
qGen();
correct();
}else{
qcount++;
incorrect();
x = questionList[qcount];
j = x.answer;
qGen();
}
})
}
clickChoice();
//timer
function time(){
timeLeft--;
$('#time').text(timeLeft);
if(timeLeft===0){
$('#score').text('TIME UP');
timer2 = setInterval(timeUp, 2000);
}
}
//time up
function timeUp(){
clearInterval(timer);
wrongQ++;
qcount++;
x = questionList[qcount];
j = x.answer;
clearInterval(timer2);
nextQ();
}
//correct
function correct(){
clearInterval(timer);
clearInterval(timer2);
$("#list").text("");
correctQ++;
nextQ();
}
//incorrect
function incorrect(){
clearInterval(timer);
clearInterval(timer2);
$("#list").text("");
wrongQ++;
nextQ();
}
//next question gen
function nextQ(){
timeLeft= 10;
$('#score').text("");
$('#ca').text("");
$('#question').text(x.q);
//$("#time").text(timeLeft);
$("#list").text("");
qGen();
}
Below is a modified version of your code, which should solve your issues.
Notes
I have made some simple assumptions about your HTML and CSS
I have not implemented score updating, but that should be straight forward given the below
const questionList = [
{
q: 'What is a dog?',
a: ['fish', 'mammal', 'plant', 'prokaryote'],
answer: 1
},
{
q: 'What is a cat?',
a: ['mammal', 'fish', 'plant', 'amphibian'],
answer: 0
},
{
q: 'What is a tree?',
a: ['plant', 'fish', 'mammal', 'none'],
answer: 0
},
{
q: 'What do cars run on?',
a: ['gasoline', 'water', 'ethanol', 'liquid oxygen'],
answer: 0
},
{
q: 'What is 4 x 4?',
a: ['8', '16', '4', '160'],
answer: 1
},
{
q: 'What is the capital of Australia?',
a: ['Brisbane', 'GoldCoast', 'Perth', 'Canberra', 'Melbourne'],
answer: 3
},
{
q: 'What is the national flower of Canada?',
a: ['sunflower', 'daisy', 'trillium', 'rose', 'lotus'],
answer: 2
}
];
//--------------------------------------
let picked;
let qcount = 0;
const output = [];
let timer;
const startingTime = 10;
let timeLeft;
let correctQ = 0;
let wrongQ = 0;
// var randomQ = Math.floor(Math.random()*7);
// let x = questionList[qcount];
// let j = x.answer;
// var cAns = x.a[j];
// console.log(cAns);
// console.log(j);
// next question gen
function nextQ() {
timeLeft = 10;
document.querySelector('#score').textContent = '';
// document.querySelector('#ca').textContent = '';
document.querySelector('#question').textContent = questionList[qcount].q;
// $("#time").text(timeLeft);
document.querySelector('#list').textContent = '';
qGen();
}
// time up
function timeUp() {
clearInterval(timer);
wrongQ += 1;
qcount += 1;
nextQ();
}
// correct
function correct() {
clearInterval(timer);
correctQ += 1;
nextQ();
}
// incorrect
function incorrect() {
clearInterval(timer);
wrongQ += 1;
nextQ();
}
// timer
function time() {
timeLeft -= 1;
document.querySelector('#time').textContent = timeLeft;
if (timeLeft === 0) {
document.querySelector('#score').textContent = 'TIME UP';
timeUp();
}
}
// Add EventListener to each button
function addEL(el) {
el.addEventListener('click', event => {
picked = parseInt(event.currentTarget.getAttribute('data-id'), 10);
console.log(`${picked} click`);
const correctAnswer = questionList[qcount].answer;
qcount += 1;
if (picked === correctAnswer) {
console.log(`${correctAnswer} if`);
correct();
} else {
incorrect();
}
});
}
// new Q w/ options
function qGen() {
const x = questionList[qcount];
timeLeft = startingTime;
document.querySelector('#time').textContent = startingTime;
document.querySelector('#question').textContent = x.q;
for (let i = 0; i < x.a.length; i += 1) {
const newLi = document.createElement('li');
const answer = document.createElement('button');
answer.setAttribute('data-id', i);
answer.classList.add('answer');
answer.textContent = x.a[i];
addEL(answer);
newLi.appendChild(answer);
document.querySelector('#list').appendChild(newLi);
}
timer = setInterval(time, 1000);
}
document.addEventListener('DOMContentLoaded', () => {
qGen();
});
.answer {
background-color: yellow;
}
<div>
Question:
<span id="question">XXX</span>
</div>
<div>
Time:
<span id="time">XXX</span>
</div>
<div>
Score:
<span id="score">XXX</span>
</div>
<div>
<ul id="list">
</ul>
</div>
Below are the changes I made, including some tips on good practices in JavaScript.
Code Logic
You are calling qGen twice, effectively spinning up two new intervals on each click
The event listener must be added to all the buttons
No need for the second timer
Only <li> elements are permitted inside <ul> / <ol>
It is perfectly fine to place other elements, like your buttons, inside those <li>s.
You can also format them differently, if you prefer (e.g. on one line)
Avoid operating on the DOM, before the DOM tree has finished loading
See the added DOMContentLoaded event listener
output, correctQ, wrongQ: These assigned values are never used in your code
Good Practices
Avoid unary operators ++ and --
Automatic semi-colon insertion could break your code
Define functions before calling them
Don't use jQuery (or other abstractions) before you are completely comfortable with vanilla JavaScript
Prefer arrow functions over anonymous functions
Use event.currentTarget instead of this inside event listener

How to save radio button choices on back and next click

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
}
});

Extendscript: how to skip current iteration in a for loop?

I have the following code, written in ExtendScript to process a series of layers in an After Effects composition:
for (var i=0; i < selectedLayers.length; i++) {
var layer = selectedLayers[i];
if (!layer.hasVideo || !layer.enabled) {
//Go for the next one
continue;
}
//Do stuff
}
If an element isn't enabled or doesn't have video in it, the loop should skip it; if it does, then it should be processed.
Now, everything works fine if there are no elements that fulfill that "if" check, but if one element fulfills that check… then the loop gets stuck at the next iteration. That is: imagine if the element at i=2 doesn't have video. The "continue" gets executed… and then, the loop gets stuck indefinitely at i=3 and never ends.
Why does this happen? I thought that "continue" is precisely the instruction to skip an iteration of a loop in Javascript/Extendscript. What's going on?
EDIT: as requested, here is my entire code. Maybe I forgot a brace somewhere in one of those nested "if"s… but in that case, how can the code work in some cases and not in others?
var nombreDelPlugin="Denoiser II";
var rutaRender="/Users/paulj";
var activeItem = app.project.activeItem;
if ((activeItem == null) || !(activeItem instanceof CompItem)) {
alert("Please select or open a composition first.");
}
else {
var selectedLayers = activeItem.selectedLayers;
if (activeItem.selectedLayers.length == 0) {
alert("Please select at least one layer in the active comp first.");
}
else {
var comp = app.project.activeItem;
var width=comp.width;
var height=comp.height;
var par=comp.pixelAspect;
var fps=comp.frameRate;
var tempFolder = comp.parentFolder.items.addFolder(comp.name + " - Temp Comps");
var ClipsAnadidos=Array();
var nombresUsados={};
for (var i=0; i < selectedLayers.length; i++) {
alert("Mooo: " + i);
var layer = selectedLayers[i];
if (!layer.hasVideo || !layer.enabled) {
alert("Meeept: " + i);
continue;
}
/* if (!esFootage(layer)) {
alert("Meeept: " + i);
break;
}
*/
//¿Hemos renderizado ya este layer? Si es así, nos lo saltamos.
var original=layer.source;
if (inArray(original, ClipsAnadidos) > 0) {
continue;
}
ClipsAnadidos.push(original);
//¿Hay otra comp ya con este mismo nombre?
var vecesUsado=nombresUsados[original.name];
if (!vecesUsado) { vecesUsado=0; }
var nombre= original.name + "_" + vecesUsado;
nombresUsados[original.name]=vecesUsado + 1;
//Creamos la nueva comp con el clip dentro
var newcomp=app.project.items.addComp(nombre, width, height, par, original.duration, fps);
var newlayer=newcomp.layers.add(original, original.duration);
newcomp.parentFolder=tempFolder;
//Si la escala no es 100, usamos la de la comp original
if ((layer.scale.value[0] != 100) || (layer.scale.value[1] != 100)) {
newlayer.scale = layer.scale.value;
}
var denoise = newlayer.property("Effects").addProperty(nombreDelPlugin);
//Añadimos al render queue, y establecemos la ruta de salida
var rqi = app.project.renderQueue.items.add(newcomp);
var om = rqi.outputModule(1); // Assumes at least one output module
om.file=new File(rutaRender + "/" + original.name);
}
}
}
function esFootage(lay) {
if (lay.source instanceof FootageItem) {
//alert(lay.name + " es footage");
if (lay.source.mainSource instanceof SolidSource) { return false; }
else { return true; }
}
if (lay.source instanceof CompItem) {
return true;
}
else { return false; }
}
function inArray(v, arr) {
for (i=0; i < arr.length; i++) {
if (arr[i] == v) { return i; }
}
return -1;
}
This works fine for me:
var selectedLayers = [
{hasVideo: true, enabled: true},
{hasVideo: true, enabled: true},
{hasVideo: true, enabled: false},
{hasVideo: true, enabled: true},
{hasVideo: false, enabled: true}
];
for (var i=0; i < selectedLayers.length; i++) {
var layer = selectedLayers[i];
if (!layer.hasVideo || !layer.enabled) {
//Go for the next one
continue;
}
//Do stuff
console.log(i);
}
It skips 2 and 4 and outputs:
0
1
3
If you have a loop within a loop it could be that the inner i is being reset, which in that case you'd have to define it outside of the loops.

Getting the last values used in a quiz with jQuery

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();
}
}
}
}

Categories