2

I am trying to create a loop to create many functions so that when a user clicks the thumb up button it runs the correct .php document. It works great when I remove the loop and just give var i a specific number but as soon as i try to make it into a loop, at the alert(i) i get 10 on the first loop.

 var i=1;
 while ( ++i < 10 ) {
    $('#thumbup' + i).click(function() {
        var userid = $('#theuser' + i).text();
        var url = "_thumbup.php?userid=" + userid;
        //alert(url);

        $('#thumbup' + i).hide();
        $('#thumbdown' + i).hide();

        $("#toggle").css("display","block");
        alert(i); // Give me 10 on first loop?!?

        // get the URL
        http = new XMLHttpRequest(); 
        http.open("GET", url, true);
        http.send(null);

        // prevent form from submitting
        return false;   

    }); 
  }
MikeBeaudin87
  • 115
  • 1
  • 6

2 Answers2

8

This is a classical problem : by the time your callbacks are called, i has the value of end of loop.

Here's how you can fix it :

var i=1;
while ( ++i < 10 ) {
   (function(i){
      // your current code
   })(i);
}

It works because the internal function creates a scope when it is called, and this scope contains the value of i you want.

Denys Séguret
  • 372,613
  • 87
  • 782
  • 758
  • works great thank you so much, i usally find the answers without asking a new question but couldn't this time around even though it was a pretty simple solution. thank you. – MikeBeaudin87 Oct 11 '13 at 12:59
  • 1
    @MikeBeaudin87 I know it's not always easy to understand what the problem is and especially here, it must be hard to know what to search for. That's why I didn't want to be harsh (I'm very harsh when I find an obviously lazy question). – Denys Séguret Oct 11 '13 at 13:00
2

You have to pass the value of i into your callback. Try this:

var i=1;
 while ( ++i < 10 ) {
    (function(i){
      $('#thumbup' + i).click(function() {
        var userid = $('#theuser' + i).text();
        var url = "_thumbup.php?userid=" + userid;
        //alert(url);

        $('#thumbup' + i).hide();
        $('#thumbdown' + i).hide();

        $("#toggle").css("display","block");
        alert(i); // Give me 10 on first loop?!?

        // get the URL
        http = new XMLHttpRequest(); 
        http.open("GET", url, true);
        http.send(null);

        // prevent form from submitting
        return false;   

      }); 
    })(i);
  }
webduvet
  • 4,220
  • 2
  • 28
  • 39