I am new to JQuery. I have two tables: table1 is hardcoded in HTML and table2 is generated using javascript from an array loaded from a csv file. After the second table is displayed, I want to highlight (and later process) the row that user clicks using a JQuery. Simplified code below.
Hardcoded table:
<table id="table1">
<tr> <td>cell1</td><td>cell2</td><td>cell3</td> </tr>
<tr> <td>cell4</td><td>cell5</td><td>cell6</td> </tr>
</table>
Generate table from an array with id "data" (works fine):
<script type="text/javascript">
function createTable(){
var content = "";
data.forEach (function(row){
content += "<tr>";
row.forEach (function(cell)
{ content += "<td>" + cell + "</td>"; });
content += "</tr>"; });
document.getElementById("table2").innerHTML = content; }
</script>
JQuery script to do whatever to a row in the table, for example display an alert when a row is clicked:
<script>
$("tr").click(function()
{
alert("do something");
});
</script>
This code doesn't work for the generated table2. It does work only if I try to highlight the whole table (using $("table")
) but not when I try to highlight any of its elements (tr, td). It works perfectly for the hardcoded table1.
I tried using different elements like $("#table2 :td")
, $("#table2 td")
and so on but to no avail. How come I can access the whole table but not its elements?