2
<button type="button" onclick="loadDoc()">Scimba text</button>

<script>
function loadDoc() {
  var xhttp = new XMLHttpRequest();
  xhttp.onreadystatechange = function() {
    for (var i = 1; i<5; i++){
      if (xhttp.readyState == 4 && xhttp.status == 200) {
        document.getElementById(i).innerHTML = xhttp.responseText;
      }
    }
  };
  xhttp.open("GET", "info1.txt", true);
  xhttp.send();
}
</script>

Hello everybody ! Need some help ... How can I make the for loop to iterate one time when I click the button and when the button is clicked for the second time the loop will iterate also the second time and so on ...?

Seth McClaine
  • 9,142
  • 6
  • 38
  • 64
JONNI CAREYN
  • 97
  • 1
  • 2
  • 8
  • 1
    You are doing it just fine. The only thing you have to be aware of is that the result is returned asynchronous. – Bas Slagter Dec 14 '15 at 18:24
  • do you see an error? Just make sure the rest of your html is right. I see you are getting an element by ID which the ID is a number. ID should start with a letter. See [this](http://stackoverflow.com/questions/7987636/why-cant-i-have-a-numeric-value-as-the-id-of-an-element) – Aᴍɪʀ Dec 14 '15 at 18:27
  • you want to increase number of iterations when you click button more and more or what? your code looks just fine – Maxim Mazurok Dec 14 '15 at 18:29

4 Answers4

2

Forget about using a loop. Loops are for when you want to immediately do something a number of times.

At its core, this comes down to incrementing a value each time the click event happens and then do something based on what that new value is.

Start by making i a variable outside the scope of the event handler function. The simple approach for this would be to make i a global.

(The nicer approach would be to use an IIFE to scope i and assign the event handler function with JavaScript instead of HTML.).

Then, inside the event handler function:

  1. increment i
  2. get the data you want
  3. put the data in the appropriate place based on the value of i
Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
1

You should use a counter.

Declare a global variable (with var) and increase it every time you loop.

Rafa Jaques
  • 115
  • 7
1

As Quentin said since you want to manually increment your loop, you no longer can use a for loop. You should do something like this http://jsfiddle.net/t97ou0ny/. This will increment count on every click, if greater than limit, resets count to 0.

HTML

<body>
  <div id="count">0</div>
  <button id="inc-btn">
    Increment
  </button>
</body>

JS

$(document).ready(function() {
  var count = 0;
  var limit = 5;
  var count_div = $('#count');
  var increment_btn = $('#inc-btn');

  increment_btn.click(function() {
    if (++count > limit) {
      count = 0;
    }

    count_div.text(count);
  });
});
Daniel Kobe
  • 9,376
  • 15
  • 62
  • 109
0

As others have said, you don't need a loop. You need something to keep track of how many times the button has been clicked.

However, this is tricky because you don't know whether the user will click the button before or after the response has returned. If they click the button before the response gets back, you need to loop when the response gets back to catch up to the number of button clicks that have already taken place. If they click the button after the response returns, you have to hold on to the response and use it upon the user's click.

A clean way to resolve this uncertainty is to use Promises. They will allow you to write the logic just once and not concern yourself with whether the response has arrived yet or not.

plnkr example

<button type="button" onclick="loadDoc()">Scimba text</button>

<script>
window.loadDoc = (function () {
    var i = 1;
    var xhttp = new XMLHttpRequest();
    xhttp.open("GET", "info1.txt", true);
    xhttp.send();

    // create a promise for the result
    var pResponse = new Promise(function (resolve) {
        xhttp.onreadystatechange = function() {
            if (xhttp.readyState == 4 && xhttp.status == 200) {
                resolve(xhttp.responseText);
            }
        };
    });

    return function () {
        if (i < 5) {
            var c = i;
            // chain off the promise once for each click
            pResponse.then(function (response) {
                document.getElementById(c).innerHTML = response;
            });
            i += 1;
        }
    };
})();
</script>
JLRishe
  • 99,490
  • 19
  • 131
  • 169