Reputation: 55
I have code similar to this:
for(i = 0; i < array_of_questions.length; i++){
// call function that gathers necessary data + appends question to screen
// Now it needs to wait until the user presses a button to continue on to the next iteration. Right now it is set up like this:
$("#submit_button").on('click', function() {
//save data
});
}
My problem now is that it calls the function correctly... for all of the iterations. The on click function defines what would happen if the button was clicked but the loop continues after that. I'm always left with the last question displayed.
What is the best approach to fix this?
Upvotes: 2
Views: 2523
Reputation: 32145
You don't need to attach the click
handler in any loop.
Use a global variable as counter for the array index and increment it whenever you click the button:
var array_of_questions = ["Question1", "question2", "question3"];
var counter = 0;
$("#submit_button").on('click', function() {
//save data
if (counter < array_of_questions.length) {
$("#display").append("<div>" + array_of_questions[counter] + "</div>");
counter++;
}
});
Demo:
var array_of_questions = ["Question1", "question2", "question3"];
var counter = 0;
$("#submit_button").on('click', function() {
//save data
if (counter < array_of_questions.length) {
$("#display").append("<div>" + array_of_questions[counter] + "</div>");
counter++;
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="submit_button">Click me!</button>
<div id="display"></div>
Upvotes: 2