CryMasK CryMasK - 2 months ago 15
HTML Question

Add onclick event to table each row

I have an HTML table dynamically generated by js, and I want to add each row an onClick event.

Like this

(because of need to pass complex parameters in my original code, I use Javascript to add onclick function):

<!DOCTYPE html>
<html>
<body>
<table align="center" id="tableID" border="1" style="cursor: pointer;">
<thead>
<th>Text</th>
<th>MoreText</th>
<th>Lorem</th>
<th>Ipsum</th>
</thead>
</table>
<br />


<script type="text/javascript">
for (var i = 0; i < 4; i++) {
document.getElementById("tableID").innerHTML += '<tr><td>Text</td><td>MoreText</td><td>Lorem</td><td>Ipsum</td></tr>';

document.getElementById("tableID").rows[i+1].onclick = function () {
alert("Hello World");
//alert(i);
};
}
</script>
</body>
</html>


If the table row is fixed and declared in HTML document, using this method is working,

but in my code (dynamically generated table row), the onClick function only works in the last row.

I guess that maybe is asynchronous problem, but I can't figure out.

UPDATE

According to @Quentin's method, I edited my code. It works fine.

<!DOCTYPE html>
<html>
<body>
<table align="center" id="tableID" border="1" style="cursor: pointer;">
<thead>
<th>Text</th>
<th>MoreText</th>
<th>Lorem</th>
<th>Ipsum</th>
</thead>
</table>
<br />

<script type="text/javascript">
for (var i = 0; i < 4; i++) {
var table = document.getElementById('tableID');

var tr = document.createElement('tr');
tr.onclick = function () {
alert("Hello World");
};

var td1 = document.createElement('td');
td1.innerText = "Text";
var td2 = document.createElement('td');
td2.innerText = "MoreText";
var td3 = document.createElement('td');
td3.innerText = "Lorem";
var td4 = document.createElement('td');
td4.innerText = "Ipsum";

tr.appendChild(td1);
tr.appendChild(td2);
tr.appendChild(td3);
tr.appendChild(td4);

table.appendChild(tr);
}
</script>
</body>
</html>

Answer

You are assigning a new value to innerHTML.

This erases all the existing DOM elements and the event handlers attached to them and creates new ones (but you haven't got any code to recreate the event handlers you are deleting).

Don't use innerHTML. Use standard DOM methods: createElement, appendChild, etc. Then you can add your new row to the table body without changing what is already there.

Comments