For Loop jumping to last item only - JavaScript

I cannot figure out why the For Loop which runs through the myQuestions array is jumping from the first item straight to the last item when used inside the .Click method at the bottom of this code block.

I’d like to have the HTML updated with the next array item each time the “next-question” button is clicked.

var scoreCountRight = 0;
var scoreCountWrong = 0;

var myQuestions = [
	{	
		number: 1,
		question: "What is the cross between a tiger and a lion called?",
		answers: {
			a: 'Tiglion',
			b: 'Liger',
			c: 'Potiglionscious'
		},
		correctAnswer: 'b'
	},
	{
		number: 2,
		question: "What is the capital of Delaware?",
		answers: {
			a: 'Lansing',
			b: 'Stolzville',
			c: 'Dover'
		},
		correctAnswer: 'c'
	},
	{
		number: 3,
		question: "What family does the Wombat belong to?",
		answers: {
			a: 'Vombatus',
			b: 'Crilinus',
			c: 'Marsinch'
		},
		correctAnswer: 'a'
	},
	{
		number: 4,
		question: "If it is 3:30pm in London, what time is it in Sydney Australia?",
		answers: {
			a: '6:30am',
			b: '2:30am',
			c: '1:30pm'
		},
		correctAnswer: 'b'
	}
]
$(document).ready(function() {
	$("#question-number").append(myQuestions[0].number);
	$("#question-text").append(myQuestions[0].question);
	$("#answer-choice-a").append(myQuestions[0].answers.a);
	$("#answer-choice-b").append(myQuestions[0].answers.b);
	$("#answer-choice-c").append(myQuestions[0].answers.c);

	$("#answer-choice-b").on("click", function(){
		scoreCountRight += 1;
		console.log(scoreCountRight);
		console.log(scoreCountWrong);
	});
	$("#answer-choice-a").on("click", function(){
		scoreCountWrong += 1;
		console.log(scoreCountRight);
		console.log(scoreCountWrong);
	});
	$("#answer-choice-c").on("click", function(){
		scoreCountWrong += 1;
		console.log(scoreCountRight);
		console.log(scoreCountWrong);
	});
});

$("#next-question").click(function(){
	for (var i=0; i < myQuestions.length; i++){
		$("#question-number").html(myQuestions[i].number);
		$("#question-text").html(myQuestions[i].question);
		$("#answer-choice-a").html(myQuestions[i].answers.a);
		$("#answer-choice-b").html(myQuestions[i].answers.b);
		$("#answer-choice-c").html(myQuestions[i].answers.c);		
	};
});






Your code is showing all of the questions, and each time it shows one question it then replaces that with the next question.
That’s why you’re only seeing the last question, as the for loop has replaced all of the previous ones immediately.

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.