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.
<tbody>
<script>
for(var i=0;i<data.length;i++){
document.write("<tr>");
document.write("<td>"+data[i]['col1']+"</td>");
document.write("<td>"+data[i]['col2']+"</td>");
document.write("<td>"+data[i]['col3']+"</td>");
document.write("<td>"+data[i]['col4']+"</td>");
document.write("<td>"+data[i]['col5']+"</td>");
}
</tbody>
</script>
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:
var table = document.getElementById("tableID");
if (table) {
for (var i = 0; i < table.rows.length; i++) {
table.rows[i].onclick = function() {
tableText(this);
};
}
}
Advertisement
Answer
Your javascript code looks correct to me but I think you’re not placing it at correct place.
Try this:
<script>
for(var i=0;i<data.length;i++){
document.write("<tr>");
document.write("<td>"+data[i]['col1']+"</td>");
document.write("<td>"+data[i]['col2']+"</td>");
document.write("<td>"+data[i]['col3']+"</td>");
document.write("<td>"+data[i]['col4']+"</td>");
document.write("<td>"+data[i]['col5']+"</td>");
}
function tableText(tableRow) {
var name = tableRow.childNodes[1].innerHTML;
var age = tableRow.childNodes[3].innerHTML;
var obj = {'name': name, 'age': age};
console.log(obj);
}
let tableData = document.getElementById('tableID').getElementsByTagName('tbody')[0];
for (let i = 0; i < tableData.rows.length; i++)
{
tableData.rows[i].onclick = function()
{
tableClicked(this);
};
}
function tableClicked(rowData) {
let msg = rowData.cells[0].innerHTML+'*'+rowData.cells[1].innerHTML+'*'+rowData.cells[2].innerHTML+'*'+rowData.cells[3].innerHTML+'*'+rowData.cells[4].innerHTML;
console.log(msg,data);
};
</script>