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{})
?
Two ways of doing this.
Use $.each
var element_array = new Array('#element1','#element2');
$.each( element_array, function( index, value ){
$(value).change(function(){
alert( index );
});
});
Create a closure.
var element_array = new Array('#element1','#element2');
for ( i = 0; i < element_array.length; i++){
(function(i){
$(element_array[i]).change(function(){
alert(i);
});
})(i);
}
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 to 2
.
You have to create a local scope that stores the value of i
at the moment your function is being created:
els = new Array('#element1','#element2');
for (i=1; i < 3; i++){
(function(i){
$(els[i]).change(function(){
alert(i);
});
})(i);
}
jQuery events can take eventData in the signiture and pass it as arguments to your callback function. From jQuery docs:
.change( [eventData], handler(eventObject) )
What you want is this (I've changed the arg name to keep it obvious):
for (i=1; i < 3; i++){
$(els[i]).change({index: i}, function(event){
alert(event.data.index);
});
}
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.