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);
});
}
});
By the time your
clickevent handler executes,$ihas reached it’s final value ($count - 1). You need to capture the value of$iat each iteration of the loop. You can do this by introducing a closure that “closes over” the value of$iat each iteration: