1
$(document).ready(function() {

allQuestions is the array of objects, which role is providing the questions(question), the answers(choices) and the correct response(correctAnswer) for my app.

        var allQuestions = [{question: "If you were a super hero what powers would you have?",
            choices: ["a", "b", "c", "d"],
            correctAnswer:0},

            {question: "Do you have a cherished childhood teddybear?",
                choices: ["e", "f", "g", "j"],
                correctAnswer:0},

            {question: "Whats your favourite non-alcoholic drink?",
                choices: ["i", "j", "k", "l"],
                correctAnswer:0},

            {question: "Are you religious?",
                choices: ["m", "n", "o", "p"],
                correctAnswer:0}];

Next, once my button, with #next id is clicked, the paragraph with id #question should change his text with the next question from the allQuestions array.

The real result? When I clicked on next button, the function iterates over all the questions and it showed the last one only.

I tried to use a solution from stackoverflow, setting a var hasLooped but doesn't work.

        $('#next').click(function(){
            //var hasLooped = false;
            $.each(allQuestions, function(key){

               // if(!hasLooped) {
                    $('#question').text(allQuestions[key].question);
               // }
               // hasLooped = true;
            })
        })
    });
Bacchus
  • 515
  • 8
  • 22

4 Answers4

1

Save index of question in a variable and increment it whenever #next is clicked.

Write this:

$(function () {
    var count = 0,
        len = allQuestions.length;
    $('#next').click(function () {
        if (count < len - 1) {
            count++;
            $('#question').text(allQuestions[count].question);
        } else {
            $(this).remove();
    });
});

fiddle

Alex
  • 11,115
  • 12
  • 51
  • 64
codingrose
  • 15,563
  • 11
  • 39
  • 58
0

You need to store the current question somewhere externally and refer to that rather than the key passed to the each function as that will always loop through all and you'll see the last one.

var intNum = 1;

$('#next').click(function(){

    $('#question').text(allQuestions[intNum].question);
    intNum++;
});
Alex
  • 7,320
  • 1
  • 18
  • 31
0
var clickCount = 0;
$('#next').click(function(){        
  $('#question').text(allQuestions[clickCount].question);       
  clickCount=(clickCount+1>9)?0:clickCount+1;
});
Gilsha
  • 14,431
  • 3
  • 32
  • 47
0

If you don't like global variables, you may try this:

$('#next').click(function(){
    var counter = parseInt($("#next").attr("counter"));
    if (counter>=allQuestions.length){
        alert("No more questions!");
        return;
    }
    $('#question').text(allQuestions[counter].question);
    $("#next").attr("counter",counter+1);
});

DEMO HERE

Carson Ip
  • 1,896
  • 17
  • 27