GabrielRado GabrielRado - 1 year ago 77
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.onclick = function(event) {

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

Answer Source

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) {

Furthermore one can set the id without setting an attribute by its property: = 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.innerHTML = i;
    tB.onclick = function(){
        console.log(i, //logs 9 (i is now statically 9) and the buttons id
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download