In this stack there's a solution to select and highlight a whole row from a table using jQuery. I have a callback (see the bottom of my script) when I click a row on the table. The problem is that my table gets generated from data, so the callback does not work on the generated cells. The callback works on the headers, which are not generated.
How to attach the existing callback to the newly generated elements?
<style>
.selected {
background-color: brown;
color: #FFF;
}
</style>
<body>
<table id="table" border="1" ContentEditable>
<tbody id="tablebody">
<tr>
<th>Date</th>
<th>Number</th>
</tr>
</tbody>
</table>
<button onclick="generateTable()">generateTable</button>
<script>
function generateTable() {
var tbl = document.getElementById('table')
var tbdy = document.getElementById('tablebody')
//Table elements
var arr={Date: "my date", Number:"my number"}
var tr = document.createElement('tr');
for (el in arr) {
var td = document.createElement('td');
var t = document.createTextNode(arr[el]);
td.appendChild(t);
tr.appendChild(td);
}
//append line to tbody
tbdy.appendChild(tr);
tbl.appendChild(tbdy);
}
jQuery("#table tr").click(function(){
console.log("this works only when clocking on the headers <th>")
jQuery(this).addClass('selected')
.siblings().removeClass('selected');
});