0

I want to write a simple HTML file containing 10 buttons, each button with text from 0 to 9, and when a button is clicked it shows on the console the number corresponding to it. The buttons have to be dynamically created in a javascript file.

Here is my code:

HTML file:

<!DOCTYPE HTML>
<head>
    <script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>  <!-- JQuery script -->
    <script src="test.js"></script>
</head>
<body>
 <div id="maindiv"></div> <!-- This div will contain the buttons. -->
</body>

Javascript (test.js) file:

$(document).ready(function () {
    DOM_ready();
});

function DOM_ready() {
    var maindiv = document.getElementById("maindiv");
    var button_create_aux;
    for (var i = 0; i < 10; i++) {
        button_create_aux = document.createElement('button');
        button_create_aux.innerHTML = i; // sets the button text corresponding to its iteration value.

        $(button_create_aux).click(function () {
            clicked(i);
        });

        maindiv.appendChild(button_create_aux);
    }
}

function clicked(num) {
    console.log(num);
}

The problem is that when I click the buttons in the HTML page, it shows always on the console the last value given to the variable i used in the for loop (in this case, 10).

It looks like that in the line clicked(i); the argument passed is the reference to the variable i, not its value, so I want a way to pass the value that i has at each iteration of the loop.

Ele
  • 33,468
  • 7
  • 37
  • 75
  • I've closed this question as a duplicate which you should read, but the short answer is to change `for(var i=0;i<10;i++){` to `for(let i=0;i<10;i++){` to avoid a common closure. – Scott Marcus Jan 02 '18 at 01:40
  • In addition to the closure note, you could also use `bind()` to approach this issue. `$(button_create_aux).click(clicked.bind(null, i));` – Taplar Jan 02 '18 at 01:41
  • @EleazarEnrique Please use the Edit privilege responsibly. Use it to correct mistakes or improve the understanding of the question/code. Do not use it to alter code to your personal preference. There was nothing wrong with the original code formatting. Your edit just changes code from 2 space indents to 4 space indents. – Scott Marcus Jan 02 '18 at 01:45
  • @ScottMarcus sorry for that, I copied in my IDE and formatted it. Thank you for advising me. – Ele Jan 02 '18 at 01:47

0 Answers0