2

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?

4
  • 1
    Don't loop at all? Do everything inside the callback function and use global var to keep track of your i. Commented Jun 3, 2017 at 23:47
  • We are not able to get your problem, please elaborate, if possible share screen shot. Commented Jun 3, 2017 at 23:53
  • @xDreamCoding although that would work, I was hoping for a solution that could be used with looping -- this sort of thing pops up quite frequently in this particular program so having a method to loop it would be very useful. Commented Jun 3, 2017 at 23:55
  • 1
    You have to grasp the concept of async programming. This won't work with any kind of loop, because callbacks aren't build for that. Commented Jun 3, 2017 at 23:56

1 Answer 1

2

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>

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.