I am trying to add events dynamically to my project. Where in multiple events are to be added. Its difficult to describe the functionality of the project so I have created a very simple example code to demonstrate the functionality I am trying to create. I am trying to create multiple event listeners to using for loop, and the body of that event listener uses the the for loop iterator variable in its execution. But, the problem is this that only the last value of the for loop is used in all the event listeners. Please refer to the code below.
<script>
function addlisteners() {
var allinputs = document.body.getElementsByTagName("input");
for ( var i = 0; i < allinputs.length; i++ ) {
allinputs[i].onclick = function() {
alert("hii, I am" + i + "input field");
}
}
}
window.onload = function() {
for ( var i = 0; i < 10; i++ ) {
var input = document.createElement("input");
document.body.appendChild( input );
}
addlisteners();
}
</script>
</head>
<body>
</body>
So, if the code is executed and tried, you will see that clicking on all the input boxes displays the last value of i, like this, "hii, I am 10 input field". Please answer if you know how to create this event handler in such a way that it displays the appropriate value of i. ie; "hii, I am 1 input field" for input box 1 and "hii, I am 2 input field" for input box 2 and so on. Thank you so much for your time.