I’ve created dynamic table rows using javascript for loop and I want to fire a click event on row in a way that whenever user clicks on any row it should be visible in console log.
JavaScript
x
13
13
1
<tbody>
2
<script>
3
for(var i=0;i<data.length;i++){
4
document.write("<tr>");
5
document.write("<td>"+data[i]['col1']+"</td>");
6
document.write("<td>"+data[i]['col2']+"</td>");
7
document.write("<td>"+data[i]['col3']+"</td>");
8
document.write("<td>"+data[i]['col4']+"</td>");
9
document.write("<td>"+data[i]['col5']+"</td>");
10
}
11
</tbody>
12
</script>
13
I know there are many answers for this but I tried and none helping me and some prints as undefined.
Here is what I tried:
JavaScript
1
9
1
var table = document.getElementById("tableID");
2
if (table) {
3
for (var i = 0; i < table.rows.length; i++) {
4
table.rows[i].onclick = function() {
5
tableText(this);
6
};
7
}
8
}
9
Advertisement
Answer
Your javascript code looks correct to me but I think you’re not placing it at correct place.
Try this:
JavaScript
1
35
35
1
<script>
2
for(var i=0;i<data.length;i++){
3
document.write("<tr>");
4
document.write("<td>"+data[i]['col1']+"</td>");
5
document.write("<td>"+data[i]['col2']+"</td>");
6
document.write("<td>"+data[i]['col3']+"</td>");
7
document.write("<td>"+data[i]['col4']+"</td>");
8
document.write("<td>"+data[i]['col5']+"</td>");
9
}
10
11
12
13
function tableText(tableRow) {
14
var name = tableRow.childNodes[1].innerHTML;
15
var age = tableRow.childNodes[3].innerHTML;
16
var obj = {'name': name, 'age': age};
17
console.log(obj);
18
}
19
20
21
let tableData = document.getElementById('tableID').getElementsByTagName('tbody')[0];
22
for (let i = 0; i < tableData.rows.length; i++)
23
{
24
tableData.rows[i].onclick = function()
25
{
26
tableClicked(this);
27
};
28
}
29
30
function tableClicked(rowData) {
31
let msg = rowData.cells[0].innerHTML+'*'+rowData.cells[1].innerHTML+'*'+rowData.cells[2].innerHTML+'*'+rowData.cells[3].innerHTML+'*'+rowData.cells[4].innerHTML;
32
console.log(msg,data);
33
};
34
</script>
35