0

I am generating html table on ajax callback like

...
success: function (data) {
    if (data != undefined) {
        var table = $("<table id='carTable' />").addClass("table table-striped table-bordered table-condensed");
        var header = $("<thead/>").html("<tr><th>a</th><th>b</th><th>c</th><th>d</th><th>e</th><th>f</th><th>g</th>");
        table.append(header);
        for (var i = 0; i < data.length; i++) {
            var row = $("<tr/>");
            row.append($("<td id='carId'/>").html(data[i].Id));
            row.append($("<td id='name'/>").html(data[i].Name));
            row.append($("<td/>").html(data[i].Color));
            row.append($("<td/>").html(data[i].Doors));
            row.append($("<td/>").html(data[i].Fuel));
            row.append($("<td/>").html(data[i].Injection));
            row.append($("<td/>").html(data[i].Desc));
            table.append(row);
        };
        $("#carsTable").html(table);
    }
},
...

On same page using javascript I want to recognize click event on table row of this carTable generated snippet.

 $('#carTable tr').on('click', function (e) {
      console.log('click!');
  });

Is this because of generated html in the callback and if it is how to solve this?

vinS
  • 1,417
  • 5
  • 24
  • 37
user1765862
  • 13,635
  • 28
  • 115
  • 220

1 Answers1

0
$(document).on('click', '#carTable tr', function(e) {
  console.log('click!');
});

Will trigger the callback function on every click that matches the selector in the second argument, no matter if it was there from first rendering the page, or added later via JavaScript.

Please note, however, that this does come with a price of internally triggering on every single click anywhere on the document and jQuery will internally check if the condition is matched.

So even better would be to delegate the click event to the table instead:

$('#carTable').on('click', 'tr', function(e) {
  console.log('click!');
});

Which is essentially the same, just not binding to every single click on the whole document.

Constantin Groß
  • 10,719
  • 4
  • 24
  • 50