0

When I use the current for loop value in my .on("click",function(){}) the value actually used is the break condition value of the for loop

var arr =["S","d","f"];

for(i=0;i<arr.length;i++)
{

$("#sng"+i).on("click",function(){
            console.log(i);  //is always 3
            console.log(arr[i]);  //is undefined as array doesnt have index 3 
        });

If the array has 4 elements then console.log(i) is always 5 etc.

The selector works properly as thats how i created the div using for loop and assigning id=sng+i. Why is this happening and how do i use the current i value.

My elements are all created dynamically.

clinnsin
  • 15
  • 4

2 Answers2

1

Keeping i a local variable is certainly a good way forward:

var arr =["S","d","f"];

arr.forEach((v,i)=>
{ $("#sng"+i).on("click",function(){
   console.log(i);
   console.log(v);
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<a id="sng0" href="#">link with s</a><br>
<a id="sng1" href="#">link with d</a><br>
<a id="sng2" href="#">link with f</a><br>
<a id="sng3" href="#">link with k</a>
Carsten Massmann
  • 26,510
  • 2
  • 22
  • 43
0

This is a problem of scoping. i will be read as the global value, regardless of what you click. Instead, use the value of the event:

var arr = ["S", "d", "f"];

for (i = 0; i < arr.length; i++) {
  $("#sng" + i).on("click", function(evt) {
    console.log(evt.target)
  });
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button id="sng0">One</button>
<button id="sng1">Two</button>
<button id="sng2">Three</button>

If you need the original array value and index, you're probably going to have to preserve them in some way. .data can help you there:

var arr = ["S", "d", "f"];

for (i = 0; i < arr.length; i++) {
  $("#sng" + i)
    .data('myIndex', i)
    .on("click", function() {
      console.log(arr[$(this).data('myIndex')])
    });
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button id="sng0">One</button>
<button id="sng1">Two</button>
<button id="sng2">Three</button>
Rich Churcher
  • 7,361
  • 3
  • 37
  • 60