Helper Helper - 15 days ago 6
jQuery Question

Issue in Button Click bind on Dom Ready

I am preparing Html table on Dom ready and trying to click the button in particular row. Below is my code.

$.ajax({
url: Url + token,
method: "POST",
async: true,
data: JSON.stringify(data),
contentType: "application/json; charset=utf-8",
success: function (Result) {
var editButton = '<input type="button" class="EditRole" value="Edit">';
$.each(Roles, function( key, Role ) {
var Action = PrepareTd(editButton);
var tr = '<tr attr-id="' + Role.RoleID + '">' + Action + "</tr>";
tbody.append(tr);
});
},
error: function (jqXHR) {
ErrorCallback(jqXHR);
}
});

$(document).ready(function() {
$('.EditRole').on("click", function() {
debugger;
console.log($(this).parent());
});
});


This never hit debugger. Am I missing something?

Answer

It's a event delegation issue Use this

$(document).ready(function() {
    $(document).on("click", '.EditRole', function() {
        console.log($(this).parent());
    });
});