I have a datatable with all the categories in my website. There is a function to delete a categori with AJAX while selecting a category to move the products(websites in my case) to another category. Here's how I do it:
$(".delete_category_instant").on('click', function(event) {
$(this).hide();
$(this).closest("td").find(".editCategory").hide();
$(this).closest("td").find(".selectCategoryToMove").removeClass("d-none");
});
$(".selectCategoryToMove").find(".submitSelection").on('click', function(event){
$(this).closest("td").find(".selectCategoryToMove").addClass("d-none");
$(this).closest("td").find(".confirmAction").removeClass("d-none");
Toast.fire({
icon: 'warning',
title: 'Please confirm your action!'
});
});
$(".confirmActionYes").on('click', function(event) {
var cat_id = $(this).attr('category-id');
var move_cat_id = $(this).closest("td").find("select").val();
$this = $(this);
$.ajax({
type: 'GET',
url: '{{ url("administrator/delete/category/") }}',
data: {
id: cat_id,
move_id: move_cat_id
},
success: function(response) {
if(response.status == 1) {
Toast.fire({
icon: 'success',
title: 'Category deleted successfully!'
});
$this.parents('tr').remove();
} else if(response.status == 2) {
Toast.fire({
icon: 'warning',
title: 'You are not allowed to do this action!'
});
} else {
Toast.fire({
icon: 'error',
title: 'Could not delete this category!<br/>Please try again later!'
});
}
},
error: function(xhr, ajaxOptions, thrownError) {
console.log(xhr.status);
console.log(thrownError);
}
});
});
$(".confirmActionNo").on('click', function(event) {
$(this).parent().addClass("d-none");
$(this).parent().closest("td").find(".delete_category_instant").show();
$(this).parent().closest("td").find(".editCategory").show();
});
But that's working only on page 1 in the datatable. Inside other pages the button isn't even responding on click. What's the solution of that? Is that a common problem that I need to be aware of in the future?
CodePudding user response:
It's possible that your event handlers are not connecting to new elements because the code that sets them up only runs once, on page load. Can't tell from your example, but if that's the case you can use delegated listeners instead:
For example:
$(".confirmActionYes").on('click', function() {...})
becomes
$(document).on('click', '.confirmActionYes', function () {...})