Igor's right about the reason (by the time the handler executes, m
has long been 27
), but I'd suggest a different solution.
If we use a different variable that does not change with the loop, you will get the expected behavior. The easiest way to do this as JavaScript has function scope is to use a function:
function attachHandler(m) {
// Since it's an argument, the m in here will initially take the value of the
// m outside, but it's not the same variable, so it won't change as the
// outside m changes.
$("#letter"+m).click(function() {
$("#letter1").attr('value', m);
j = 0;
setValue(this.value, length);
changeImage("#img");
});
}
for(var m=1;m<=26;m++) {
attachHandler(m);
}
A common idiom for this is to use an immediately-invoked function expression:
for(var m = 1; m <= 26; m++) {
(function(m) {
$("#letter"+m).click(function() {
$("#letter1").attr('value', m);
j = 0;
setValue(this.value, length);
changeImage("#img");
});
})(m);
}