I have the following code:
$(":input, textarea, select").on('blur', function(ev) {
var data = $('#campaign-form').serialize();
$.ajax({
url: "/campaign/validate",
type: "POST",
data: data,
cache: false,
dataType: 'json',
success: function (data) {
if (data) {
/*Assign error classes*/
$.each(data, function (field, message) {
jQuery("#" + field).addClass('input-error');
jQuery("#" + field + "-error").text(message);
})
}
}
});
This code adds a class 'input-error' to fields which have an error (validated on the PHP side).
The issue is that if I fix the error, and send validation again, the input-error class is not removed. Also I need to add class input-valid to the correct fields.
I have tried a solution, but it does not look optimal (it does make the work though).
$(":input, textarea, select").on('blur', function(ev) {
var data = $('#campaign-form').serialize();
$.ajax({
url: "/campaign/validate",
type: "POST",
data: data,
cache: false,
dataType: 'json',
success: function (data) {
if(data) {
/*Remove classes for all fields in the form*/
clearFields = $("#campaign-form :input.gg-field, #campaign-form textarea.gg-textarea, #campaign-form select.gfp-field").each(function(index) {
var input = $(this);
var fieldId = input.attr('id');
jQuery("#"+fieldId).removeClass('input-valid');
jQuery("#"+fieldId).removeClass('input-error');
jQuery("#"+fieldId+"-error").text("");
});
/*Assign error classes*/
$.each(data, function(field, message) {
jQuery("#"+field).addClass('input-error');
jQuery("#"+field+"-error").text(message);
})
/*To the other fields assign valid classes*/
validFields = $("#campaign-form :input.gg-field, #campaign-form textarea.gg-textarea, #campaign-form select.gfp-field").not( ".input-error" ).each(
function(index) {
var input = $(this);
var fieldId = input.attr('id');
jQuery("#"+fieldId).addClass('input-valid');
jQuery("#"+fieldId+"-error").text("");
});
}
}
});
I would like to verify which fields are coming on the data JSON object in order to assign the error or valid class in that process, avoiding the need to loop through the fields again.
Data object example:
{ "title":"* The Campaign Title field is required.",
"description":"* The Description field is required.",
"campaign_category_id":"* The Campaign Category field is required."
}