Pouya Pouya - 29 days ago 5
jQuery Question

how add event Click for dynamic tr in table

i have html table and add in table row in runtime. i want to add to new tr(dynamic tr) add ClickEvent
i write this code, but it's not work

$("#GridView1 tbody tr").click(function (e) {

var id = $(this).find(".lbl").text();
workOrderId = id;
// $("#gridtbl tr").remove();
$.ajax({
url: "PublicHandler.ashx",
contentType: "application/json; charset=utf-8",
data: { workOrderId: id },
success: function (data) {
var grd = $("#gridtbl");
$.each(data, function (i, b) {
var str = "<tr>";
str += "<td style='display: none;'>" + b.WorkId + "</td>";
str += "<td>" + b.WorkName + "</td>";
str += "<td>" + b.SectionName + "</td>";
str += "<td>" + b.SectionSupervisor + "</td>";
if (b.RequestCount == null) {
str += "<td>" + " " + "</td>";
} else {
str += "<td>" + b.RequestCount + "</td>";
}

str += "<td>" + " " + "</td>";

str += "</tr>";
$(str).click(function () {
alert("hiiiiiiiiiii");

}).end().appendTo("#gridtbl tr");
// grd.append(str);

});
},
dataType: "json"

});
popup(e);
});

Answer

you can use delegate

$("#GridView1 tbody").delegate("tr", "click", function(e) {
  //rest of the code here
});

or lately in jquery 1.7 you can use on

$("#GridView1 tbody").on("click", "tr", function(e){
    //rest of the code here
});

as mentioned in the comments by @Matt the live method is deprecated to its better not to use but i'll leave the example intact

  $("#GridView1 tbody tr").live("click",function (e) {
Comments