GabrielRado GabrielRado - 8 days ago 7
Javascript Question

How to refer to a different onclick method for each of the dynamically created buttons?

I have a script that creates a table with JSON data. Inside each row, I have two texts and one button. Button's onlick method should go to other HTML page that will be filled with two texts from same row on previously table.
First, I'm trying to print to console different texts on different button's onclick. Here's the piece that should do it:

for ( var i in json) {
var row = table.insertRow(0);
var cel1 = row.insertCell(0);
var cel2 = row.insertCell(1);
var cel3 = row.insertCell(2);
cel1.innerHTML = json[i].nome;
cel2.innerHTML = json[i].idade;
var b = document.createElement("BUTTON");
var idd = "id" + i;
b.setAttribute("id", idd);
var t = document.createTextNode("Loja");
b.appendChild(t);
b.onclick = function(event) {
console.log(idd);
}
cel3.appendChild(b);


Although this creates a table correctly with all correct id's, all button's press print the last
idd
value, and not the one that matches the id button. Anyone knows how to solve this or a better way to implement it?

Answer

The main problem I see is, that you are logging the variable idd. This variable has a static value after the for loop and by the time you click the button.

Instead you should try:

b.onclick = function(event) {
    console.log(this.id);
}

Furthermore one can set the id without setting an attribute by its property:

b.id = idd;

Here is an example to easily visualise it:

for(var i=0, j=9; i<j; i++){
    var tB = document.body.appendChild(document.createElement('button'));
    tB.id = tB.innerHTML = i;
    tB.onclick = function(){
        console.log(i, this.id) //logs 9 (i is now statically 9) and the buttons id
    }
}
Comments