Reputation: 221
It's not clear to me how i can remove a class that is added by an ajax success function. I have this code:
$.ajax({
dataType: "json",
[...]
success:function(data) {
for (var i = 0; i < data.length; i++) {
$('[name="'+data[i]+'"]').addClass('tmvc_err');
}
},
});
It basically add a red border to those fields that doesn't pass my php validation script. Now, i'm tryin to remove that red border (or better, tryin to remove class .tmvc_err) after change event. This is not working:
$(".tmvc_err").on('change', function() {
$(this).removeClass('tmvc_err');
});
It is in a document ready, so i guess the problem is that as the class is added by ajax after the document has come ready, it doesn't find that class. So, how can i fire it?
Upvotes: 0
Views: 3800
Reputation: 38112
Try to use event delegation here since your class have been added dynamically:
Event delegation allows us to attach a single event listener, to a parent element, that will fire for all children matching a selector, whether those children exist now or are added in the future.
$("body").on('change','.tmvc_err', function() {
$(this).removeClass('tmvc_err');
});
Upvotes: 2
Reputation: 148150
You need event delegation for dynamically added elements
$(document).on('change', ".tmvc_err", function() {
$(this).removeClass('tmvc_err');
});
Delegated events
Delegated events have the advantage that they can process events from descendant elements that are added to the document at a later time. By picking an element that is guaranteed to be present at the time the delegated event handler is attached, you can use delegated events to avoid the need to frequently attach and remove event handlers, jQuery docs
Upvotes: 2
Reputation: 44740
If that is added dynamically, you need event delegation -
$(document.body).on('change','.tmvc_err', function() {
$(this).removeClass('tmvc_err');
});
Upvotes: 1