I have a form with required fields which check via PHP. Which generates response in JSON and delivers it via ajax response, in following form Object {first_name: true, e_mail: false, phone_number: true, themessage: true}
the input fields in the form have the ID which is equal to key of object array.
What I am trying to achieve is to loop through this object array, determine which of the fields is missing and add error message here is how I am doing it.
if (fields_list) {
console.log(fields_list);
for (var key in fields_list) {
var item = fields_list[key];
if (item === true) {
$('#' + key).after('<div class=' + key + '>' + data.field_msg + '</div>');
} else {
$("div" + '#' + key).remove();
};
}; // Loop through fields_list
}; // if field list exist
When doing first form submision it gives me the result which I expect, it adds the div container with error message and with id of the input field after the input field itself. The problem ocurs after second submit if data has been entered into the field, I want that div container after input field to be removed. Instead it keeps appending the div container after field which still submitted without data but doesn't append additional div container to field that has data. How to fix this problem?
Thank you in advance.