Creating jquery click functions with a for loop

I am trying to create a function that adds an extra text field when the user clicks a button. Principle of work: four text fields and three buttons. Three of the four text fields are hidden using "display: none" and two of the three buttons are hidden. When you press button 1, text box 2 and button 2 appear, and when you press button 2, text box 3 and button 3, etc. appear. This is manageable by manually entering the code, but it becomes a burden when you need to create many text fields. So far I have used this code:

<html> <head> <style type="text/css"> .hide {display:none;} </style> <script type="text/javascript" src="jquery.js"></script> <script type="text/javascript"> $(document).ready(function(){ $("#add"+2 ).click(function(){ $("#add"+2).hide(); $("#text"+2).show(); $("#add"+3).show(); }); $("#add"+3 ).click(function(){ $("#add"+3).hide(); $("#text"+3).show(); $("#add"+4).show(); }); $("#add"+4 ).click(function(){ $("#add"+4).hide(); $("#text"+4).show(); }); }); </script> </head> <body><div id="border"> <form action="" method="post"> <table> <tr> <td> <input type="text" id="text1" name="text1" /> </td> <td> <input type="button" id="add2" name="add" value="add another field" /> <input type="button" id="add3" class="hide" name="add" value="add another field" /> <input type="button" id="add4" class="hide" name="add" value="add another field" /> </td> </tr> <tr> <td> <input type="text" id="text2" class="hide" name="text2" /><br> <input type="text" id="text3" class="hide" name="text3" /><br> <input type="text" id="text4" class="hide" name="text4" /> <td> </tr> </table> </form> </div> </body> </html> 

Then i replaced

  $("#add"+2 ).click(function(){ $("#add"+2).hide(); $("#text"+2).show(); $("#add"+3).show(); }); $("#add"+3 ).click(function(){ $("#add"+3).hide(); $("#text"+3).show(); $("#add"+4).show(); }); 

with a for loop to try to do the same

 var i = 2; for (i=2; i<=3; i++) { $("#add"+i ).click(function(){ $("#add"+i).hide(); $("#text"+i).show(); $("#add"+(i+1)).show(); }); } 

after replacing in a for loop, after pressing the first button, only the fourth text field is displayed. Is there some kind of logic that I don't understand here? Thanks in advance.

+4
source share
2 answers

Your inner function has a closure of the outer i , so when it accesses i , it accesses the variable itself, not its value.

You can break this down with the self-emitting function and pass the value of the new local variable.

 var i = 2; for (i = 2; i <= 3; i++) { (function(j) { $("#add" + j).click(function() { $("#add" + j).hide(); $("#text" + j).show(); $("#add" + (j + 1)).show(); }); })(i); } 
+13
source

You can check this out:

 $(':button').click(function(e) { var index = $(e.target).index(); $('.add:eq(' + index + ')').hide(); $('input:text:eq(' + (index + 1) + ')').show(); $('.add:eq(' + (index + 1) + ')').show(); }); 
0
source

All Articles