1

Look at the following code.

for(i=1;i<=10;i++){
    $('#field'+i).click(function(){
        alert(i);
    });     
}

When I click one of those fields I get an 11. Of course I know why: Because at the moment I click it the value of the variable i is 11. But I guess you know what I actually want. How do I do that?

principal-ideal-domain
  • 3,998
  • 8
  • 36
  • 73

4 Answers4

1

Use let to limit your i within the loop scope. That would solve your problem.

for(let i=1;i<=10;i++){
    setTimeout(function(){
        console.log(i)
    }, 500);     
}
Prasanna
  • 4,125
  • 18
  • 41
0

From what I see you want to get the specific field id.

I would do something like this:

for(i=1;i<=10;i++){
    $('#field'+i).click(function(){
        var id = $(this).attr("id").replace("field", "");
        alert(id);
    });     
}

Basically what you're doing in your code is that you are telling the button to alert the current value of i when clicked.

Mihail Minkov
  • 2,463
  • 2
  • 24
  • 41
0

Create a closure with IIFE:

for(i=1;i<=10;i++){
  (function(j){
    $('#field'+j).click(function(){
        alert(j);
    });
   })(i);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button id="field1">1</button>
<button id="field2">2</button>
<button id="field3">3</button>
<button id="field4">4</button>
<button id="field5">5</button>
<button id="field6">6</button>
<button id="field7">7</button>
<button id="field8">8</button>
<button id="field9">9</button>
<button id="field10">10</button>
Sebastian Kaczmarek
  • 8,120
  • 4
  • 20
  • 38
-1

You can solve it with an Immediately-invoked Function Expression.

for(i=1;i<=10;i++){
  $('#field'+i).click(function(j){
     return () => alert(j);
  }(i));     
}
alayor
  • 4,537
  • 6
  • 27
  • 47