+ 2

How to assign button id within "for" loop?

<div id="field1"></div> <script> for(i=1;i<=3;i++){ var form=document.getElementById("field1"); var button1=document.createElement("button"); var node1=document.createTextNode("Button "+i); button1.appendChild(node1); // How to assign button id within "for" loop? button1.onclick=function(){alert("Button "+i+" was clicked!");}; form.appendChild(button1); } </script>

14th Apr 2017, 1:34 PM
Doniyor Djalilov
2 Answers
+ 4
Replace button1.onclick line with button1.onclick=(function(j){return function(){alert("Button "+j+" was clicked!");};})(i) Your click handlers were working, but it was showing 4 every time because the time you click it i is 4. So, to prevent that you need to do like this. For more info, you can read about loopholes of closures inside loop.
14th Apr 2017, 2:17 PM
Ashwani Kumar
Ashwani Kumar - avatar
+ 2
It works, thank you!
14th Apr 2017, 4:20 PM
Doniyor Djalilov