Reputation: 525
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";
};
}
Upvotes: 1
Views: 1390
Reputation: 144659
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]);
Upvotes: 2
Reputation: 186
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?
Upvotes: 0
Reputation: 20970
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...";
};
}
Upvotes: 1