0

I'm trying to assign a different number to different callback functions in jquery.

for (i=o;i<types.length;i++) {
     $('#ajax'+types[i]+'Div').html('Loading...').load('searchAjax.php','new=u',function () { $(this).find('select').change( function() { AjaxDiv(i); } ) } );
}

Everytime I run this section of code, i is 5 for each call to ajaxDiv because it is calling a global variable. I'm not sure if I can either change the scope of i or if there's a way to print the value in the change function. Any ideas?

Thank you in advance! Happy Thanksgiving!

Andrew

Robert Harvey
  • 178,213
  • 47
  • 333
  • 501
Andrew
  • 1
  • See http://stackoverflow.com/questions/1451009/javascript-infamous-loop-problem and http://stackoverflow.com/questions/341723/event-handlers-inside-a-javascript-loop-need-a-closure and about 80 other questions. (Hint: you need a closure) – Crescent Fresh Nov 26 '09 at 15:52
  • While the others have certainly answered the question, another problem might be that you've set i equal to the letter o... – Gausie Nov 26 '09 at 16:34

1 Answers1

3

The callback functions all refer to the same i variable, and they are executed when the loop is finished.

You have to capture the i variable on the loop:

for (i=o;i<types.length;i++) {
  (function (i) {
     $('#ajax'+types[i]+'Div').html('Loading...').load('searchAjax.php','new=u',
     function () {
       $(this).find('select').change( function() { AjaxDiv(i); } )
     } );
  })(i);
}
Christian C. Salvadó
  • 807,428
  • 183
  • 922
  • 838
  • How many times have you explained this on SO? We need this in the FAQ badly. – Crescent Fresh Nov 26 '09 at 15:54
  • 4
    Yes, too many times, a FAQ by language would be nice... http://stackoverflow.com/questions/1734749/ http://stackoverflow.com/questions/643542/ http://stackoverflow.com/questions/1582634/ http://stackoverflow.com/questions/1331769/ http://stackoverflow.com/questions/1552941/ http://stackoverflow.com/questions/750486/ http://stackoverflow.com/questions/933343/ http://stackoverflow.com/questions/1579978/ http://stackoverflow.com/questions/1413916/ – Christian C. Salvadó Nov 26 '09 at 15:58
  • 1
    Holy crap. Do not ever delete that comment. There's the reference point right there. – Crescent Fresh Nov 26 '09 at 16:05