I have this fiddle: http://jsfiddle.net/yub2B/4/
HTML:
<input type="text" />
<input type="text" />
<input type="text" />
<input type="text" />
JS:
function test(x)
{
alert(x);
}
var text=document.getElementsByTagName("input");
for(var i=0,l=text.length;i<l;i++)
{
text[i].addEventListener("keydown",function()
{
test(i);
},false);
}
And instead of outputing 0 for first textbox, 1 for second textbox … it always ouput 4.
How can I fix this?
That’s infamous loop problem when assigning events inside loop. You are passing same value of
ion each iteration, use this:Updated Fiddle