I'm trying to attach a dynamic .change()
function to a list of elements:
els = new Array('#element1','#element2');
for (i=1; i < 3; i++){
$(els[i]).change(function(){
alert(i);
});
}
This does not work as desired because i
is not passed into the function, but is instead always equal to the last iteration, ie, 2. How do I pass a value into the change(function{})
?
Have you tried something like that:
els = new Array('#element1','#element2');
for (i=1; i < 3; i++){
$(els[i]).bind( 'change', function(){
alert(i);
});
}
When you load the page, jQuery does not know the array's values and it is like a string.
jQuery events can take eventData in the signiture and pass it as arguments to your callback function. From jQuery docs:
What you want is this (I've changed the arg name to keep it obvious):
Two ways of doing this.
All of your generated functions refer to the same variable:
i
. This variable subsequently changes when the loop continues, so that by the time your change event fires,i
will be set to2
.You have to create a local scope that stores the value of
i
at the moment your function is being created: