1

I'm trying to make the onclick event work for all rows of a table. But, it doesn't matter what row I click, the event only seems to fire for the last tr. I made a simple example to illustrate the problem on JSFiddle.

HTML:

<table>
  <tr>
    <td>Test</td>
    <td>Test2</td>
  </tr>
  <tr>
    <td>Test</td>
    <td>Test2</td>
  </tr>
  <tr>
    <td>Test</td>
    <td>Test2</td>
  </tr>
  <tr>
    <td>Test</td>
    <td>Test2</td>
  </tr>
</table>

Javascript:

var table = document.getElementsByTagName( "table" )[0];
for( var contador = 0; contador < table.getElementsByTagName( "tr" ).length; contador++ ){
  var line = table.getElementsByTagName( "tr" )[contador];
  line.onclick = function() {
    line.innerHTML = "Row clicked";
  };
}
Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
user3753202
  • 517
  • 7
  • 14

3 Answers3

2

This is a scoping issue, for block doesn't create a new scope, so the last value overrides the previous values, you can use a self-invoking function:

(function (line) {
    line.onclick = function () {
        //line.innerHTML = "Row clicked";
        line.cells[0].textContent = "Row clicked";
     };
})(table.getElementsByTagName("tr")[contador]);

http://jsfiddle.net/tx3s580a/

Ram
  • 143,282
  • 16
  • 168
  • 197
1

as mentioned in undefined's answer, for block doesn't create a new scope.

line gets changed every time the loop is run. Use this instead...

var table = document.getElementsByTagName( "table" )[0];
for( var contador = 0; contador < table.getElementsByTagName( "tr" ).length; contador++ ){
    var line = table.getElementsByTagName( "tr" )[contador];
    line.onclick = function(){
        this.innerHTML = "Row clicked...";
    };
}

http://jsfiddle.net/a9xf0nz2/

anishsane
  • 20,270
  • 5
  • 40
  • 73
0

Others replied faster than me, but once you have fixed your issue, also pay attention to the fact that your "innerHTML" will probably not work correctly with IE (your jsfiddle gives a "SCRIPT600: Invalid target element for this operation" in mine)!

JavaScript innerHTML is not working for IE?

Community
  • 1
  • 1