0

My javascript loop is not working properly. I am getting only the final value of $i.

$(function() {
    var $count = $('#count').val();
    for (var $i = 1; $i < $count; $i++) {
        var btnRemove = $('#removeImage' + $i);
        var profilepictureid = $('#profilePitcureID' + $i).val();
        btnRemove.click(function() {
            alert($i);
        });
    }
});​
nbrooks
  • 18,126
  • 5
  • 54
  • 66
Mansoor
  • 130
  • 1
  • 11

1 Answers1

3

By the time your click event handler executes, $i has reached it's final value ($count - 1). You need to capture the value of $i at each iteration of the loop. You can do this by introducing a closure that "closes over" the value of $i at each iteration:

for(var $i=1; $i<$count; $i++) {
    var btnRemove=$('#removeImage'+$i); 
    var profilepictureid = $('#profilePitcureID'+$i).val();

    (function ($i) {
        btnRemove.click(function(){
            alert($i);
        });
    }($i));
}       
James Allardice
  • 164,175
  • 21
  • 332
  • 312
  • @Mansoor: just for supplement, check this topic http://stackoverflow.com/questions/4472528/javascript-jquery-closure-function-syntax, for explanation what jquery closure function syntax is (unless you already know) - that's what I did after reading this answer – jwaliszko Nov 19 '12 at 11:39