Reputation: 470
On load page I am appending the comments via AJAX
call and all the comments have been successfully posted. All the comments have their respective delete buttons with the common class and unique ids.
So Onclick
of delete button I want to delete the respective comment but however its access is not coming into the AJAX
call. I have tried with alert as well but its not working I don't know why.
What I am doing wrong?
<script>
$(document).ready(function () {
var AddtasksId = $('#submitBtn4comment').attr('data-taskId');
$.ajax({
type: "GET",
url: "/getComments",
dataType: "json",
data: {
AddtasksId: AddtasksId
},
contentType: "application/json",
success: function(response){
$.each(response, function(key,comment) {
appendToDom(comment);
});
}
});
});
function appendToDom(data) {
let lTag = document.createElement('li')
lTag.classList.add('comment', 'mb-3')
let markup = `
<div class="card border-light mb-3">
<div class="card-body">
<h5>${data.username}</h5>
<p style="background-color:#E8E8E8">${data.comment}</p>
<div><h6>⏲️ ${data.commentDate}<span class="pull-right"></span></h6></div>
<a href="/deleteComment" id="${data._id}" class="deleteComments">Delete Comment</a>
<div id="line"><hr style="" /></div>
</div>
</div>
`
lTag.innerHTML = markup
$(".comment__box").prepend(lTag);
}
</script>
html div tags where it is appending:
<div class="row">
<div class="col-md-12">
<!-- <div class="typing text-success"></div> -->
<ul class="comment__box commonText">
</ul>
</div>
</div>
This is AJAX
call for deleting the comment:
but on clicking the <a>
button the access is not coming means alert
doesn't popup.
$(".deleteComments").on("click", function() {
alert("First alert");
var id = $(this).prop("id");
var AddtasksId = $('#submitBtn4comment').attr('data-taskId');
$.ajax({
type: "GET",
url: "/deleteComment",
dataType: "json",
data: {
AddtasksId: AddtasksId,
id:id
},
contentType: "application/json",
success: function(response){
if(response.status == 200)
window.location.reload();
}
});
})
Upvotes: 1
Views: 1211
Reputation: 2347
The click event is not triggered because the element does not exist when the event is defined.
you can solve that this way:
$(document).on("click", ".deleteComments", function() {
Upvotes: 2