-3
$(document).ready(function() {

    for (i=1;i<= 12;i++) {

        $(".panel" + i).click(function() {
           $("#panel").val($(".for-panel" + i).text()); 
        });
    }

});

This code is not working.

Where is the problem from?

  • Does this answer your question? [onClick event in a For loop](https://stackoverflow.com/questions/15860683/onclick-event-in-a-for-loop) – Alon Eitan Dec 08 '19 at 16:01
  • @AlonEitan That's the question about the array! – Mahdi Hosseinpour Dec 08 '19 at 16:08
  • This is probably a duplicate of [closures in loops](http://stackoverflow.com/questions/750486/javascript-closure-inside-loops-simple-practical-example), see the answers there for details. Note, though, that in your case, your code is falling prey to what I call [*The Horror of Implicit Globals*](http://blog.niftysnippets.org/2008/03/horror-of-implicit-globals.html). You need to declare `i`. Unless you need to support IE11 and earlier, use `for (let i = 1`... If you need to support IE11 and earlier (without transpiling e.g. via https://babeljs.io), again, see the linked question's answers. – T.J. Crowder Dec 08 '19 at 16:10
  • Another avenue to take might be to avoid setting up so many onclick event handlers altogether and instead define a single "delegated" event using jQuery's `on()` method: ... `$('body').on('click','[class^=panel]', function(ev){...})`. – Carsten Massmann Dec 08 '19 at 16:16

1 Answers1

0

Here the for loop runs first and updates the value of i to 13 when it's execution is over. But the function inside $(".panel" + i).click() will trigger only after clicking the button. At that time the value of i will be 13.

You can avoid this situation by using jquery data- attribute.

HTML

<button class="panel" data-id="1">Panel1</button>
<button class="panel" data-id="2">Panel2</button>
<button class="panel" data-id="3">Panel3</button>
.
.
<button class="panel" data-id="13">Panel13</button>

Jquery

$(document).ready(function() {
   $(".panel").click(function() {
       var i = $(this).data('id');
       $("#panel").val($(".for-panel" + i).text()); 
   });
});

For reference : https://api.jquery.com/data/