Onclick dynamically added with javascript to td element doesn't work

10,510

Solution 1

A quick JSFiddle shows that the basic approach is fine--at least in Chromium.

tbody_x = document.getElementById('x');
tbody_x.innerHTML = '';

for (row = 0; row < 5; row++)
{
  tr = document.createElement('tr');

  for (col = 0; col < 10; col++) 
  {
    td = document.createElement('td');
    td.setAttribute('name', 'r' + row + 'c' + col);
    td.onclick = function() { ChangeNumber('hi'); };
    td.innerHTML = '0';
    tr.appendChild(td);
  }

  tbody_x.appendChild(tr);
}

Something else must be broken. (Try firing up Firebug or similar and look for JS errors in the console.)

Solution 2

You could also use:

td.onclick = ChangeNumber;

the ChangeNumber is a function that could also be bind to the click, if you place this function inside you could make a custom function for each onclick.

I know what problem he's facing and it just that the onclick function wont poppup, it doesn't show any logs and if you use the td.onclick = ChangeNumber(); then it would just fire this function once when loading this script,

Share:
10,510
Johhny-T
Author by

Johhny-T

Updated on June 04, 2022

Comments

  • Johhny-T
    Johhny-T almost 2 years

    I have a problem trying to figure out why my dynamically added onclick event doesn't do anything. I have searched many sites already but nothing I tried worked. Knowing myself it is probably some kind of stupid mistake but I really want to know what I did wrong. This is a part of my code including relevant functions:

            function ChangeNumber(line){   //this is just a test function so far :)
                document.getElementById('maincol').innerHTML += line + "<br/>"; //just adds "something to the end of a div"
            }
    
            function ChangeSize()
            {
                var rows, cols;
                rows = document.getElementById('rows').value;
                cols = document.getElementById('cols').value;
    
                var tbody = document.getElementById('model');
                tbody.innerHTML = "";
    
                for (var i = 0; i < rows; i++){
                    var tr = document.createElement('tr');
                    for (var j = 0; j < cols; j++){
                        var td = document.createElement('td');
                        td.setAttribute('name', (i * cols) + (j + 1));
                        td.onclick = function() {ChangeNumber('something'); };
                        td.innerHTML = "0";
                        tr.appendChild(td);
                    }
                    tbody.appendChild(tr);
                }
    
            }
    

    The creation of the table works fine and so does call to the function ChangeNumber() from statically created onclick but when I click on the dynamically created td nothing happens. Can someone please clarify the problem to me?