li x li x - 6 months ago 8
jQuery Question

jQuery events wont execute after reapplying class selectors

Okay so I have a problem where I am using buttons on a custom form that execute two AJAX methods, Both these functions work when first selected in the correct fashion. The problem I'm having is after trying to execute the same function again after adding / removing classes that have the event handlers on them they fail to execute again meaning they only have a single life span and can't be used again.

From my research I have found that this problem is jQuery event delegation and after reading the documentation I changed my original click functions to on functions which should reapply the event handlers after the change from my understanding.

$(document).ready(function () {
$(".checkButton").on('click', function () {
var objID = this.id;
$.ajax({
url: "index.php?system=testimonials&task=update",
type: 'POST',
data: {val: objID},
success: function (data, textStatus, jqXHR)
{
$("#testimonialSpan" + objID).removeClass("label-warning");
$("#testimonialSpan" + objID).addClass("label-success");
$("#testimonialSpan" + objID).text("Approved");
$("#testimonialTick" + objID).removeClass("fa-check");
$("#testimonialTick" + objID).addClass("fa-times");
$("#" + objID).removeClass("checkButton");
$("#" + objID).addClass("timesButton");
},
error: function (jqXHR, textStatus, errorThrown)
{
alert(textStatus + errorThrown + jqXHR);
}
});
});

$(".timesButton").on('click', function () {
var objID = this.id;
$.ajax({
url: "index.php?system=testimonials&task=update",
type: 'POST',
data: {times: objID},
success: function (data, textStatus, jqXHR)
{
$("#testimonialSpan" + objID).removeClass("label-success");
$("#testimonialSpan" + objID).addClass("label-warning");
$("#testimonialSpan" + objID).text("Pending");
$("#testimonialTick" + objID).removeClass("fa-times");
$("#testimonialTick" + objID).addClass("fa-check");
$("#" + objID).removeClass("timesButton");
$("#" + objID).addClass("checkButton");
},
error: function (jqXHR, textStatus, errorThrown)
{
alert(textStatus + errorThrown + jqXHR);
}
});
});
});


I believe I am close but I have not been able to make this function as expected.

Answer

use $(document).on('click', '.checkButton', function(){}); instead of $(".checkButton").on('click', function(){}); and $(document).on('click', '.timesButton ', function(){}); instead of $(".timesButton").on('click', function () {});

It binds event to the document not to the element. so whenever you click on element with the selector it fires.