0

I have multiple buttons on a page and want them to perform similar tasks. In PHP I can manage to do so, but in JavaScript I can't seem to get it working:

for (i= 0; i<5; i++){
  $("#btn_"+i).click(function(){
    alert(i);                                 
  });
}

The alert is always 5

My PHP solution is working fine, but I want to cut back on code written on the page...

<?php
for ($i= 0; $i<5; $i++){
?>

  $("#btn_page-<?php print $i; ?>").click(function(){
    $("#btn_"+i).click(function(){
      alert("<?php print $i; ?>");                                 
    });

<?php
}
?>
ultranaut
  • 2,132
  • 1
  • 17
  • 22
kloewer
  • 1,016
  • 1
  • 9
  • 7

3 Answers3

2

You need closures for that. You can pass the reference inside the event data with jQuery, too:

for(i = 0; i < 5; i++) {
    $("#btn_"+i).click({ counter: i }, function(e) {
        alert(e.data.counter);                                 
    });
}

Here's a jsFiddle.

BenM
  • 52,573
  • 26
  • 113
  • 168
1

Not an answer to your looping problem, but you can try this method rather than looping:

$('[id^="btn_"]').click( function(e) {
    alert(this.id.replace("btn_",""));                                 
});

Sample

Anujith
  • 9,370
  • 6
  • 33
  • 48
  • 1
    Other answers explain how the problem is due to variable scoping, and this answer is IMO the best approach to get the desired bahavior. Indeed, jQuery fixes in its callbacks the `this` keyword so that it refers to the calling DOM element. – Gras Double Mar 10 '13 at 14:37
  • 1
    Used this version as the best solution for my case! THNX a lot! – kloewer Mar 10 '13 at 14:41
  • Chose BenM's answer as the solution to my original question though... – kloewer Mar 10 '13 at 14:42
0

This is a well-known for loop problem. You need to envelope your code in a self-executing closure.

$("#btn_" + i).click(function(i) {
     return function() {
         alert(i);
     };
}(i));

Or you can place an executing callback into the parameters like this:

$("#btn_" + i).click(callback(i));

function callback(i) {
    return function() { alert(i); };
}

All the details are explained in the duplicate.

Community
  • 1
  • 1
David G
  • 94,763
  • 41
  • 167
  • 253