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.