0

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?

aethalyste
  • 27
  • 6

4 Answers4

3

You need event delegation for dynamically generated element. Try like below.

$('body')on('click', 'tr', function() {
    alert("do something"); 
});
Ibrahim Khan
  • 20,616
  • 7
  • 42
  • 55
1

For dynamically created elements, you need to use:

$('body').on("click", "#your_element",function(){

});

OR

$("#your_element").on("click",function(){

});
0

Reason why your click does not work is because,

$("tr").click(function(){...})

This event is registered on all existing elements but your dynamic rows are yet to be rendered. For this reason you should use delegates.

You can do something like:

$(document).on("click", "tr", function(){...})

But since you already have ID, you should try:

$("#table2").on("click", "tr", function(){...});
Rajesh
  • 24,354
  • 5
  • 48
  • 79
0

Use live for dynamically added content.

$('#table2 tr').on( 'click', function(){
    alert("do something"); 
    console.log(this)
});
Chintan Mirani
  • 1,464
  • 9
  • 18