Solution:
Remove the error every time, and only add it back if the checkbox isn’t checked. You don’t need an if/else condition.
// Form submission
$('form.checkout').on('submit', function () {
let valid = true;
// Validate all checkboxes in the form
$(this).find('input:checkbox').each(function () {
// Start by removing any previous error
removeCheckboxError(this);
// Add a new error if the checkbox is unchecked
if (!$(this).is(':checked')) {
$(this).parent().after('<span class="error">This field is required...</span>');
valid = false;
}
});
// Only allow the form to submit if all checkboxes were valid
return valid;
});
// Remove error from a checkbox when clicked
$('form.checkout input:checkbox').click(function () {
removeCheckboxError(this);
});
// Reusable function to remove errors
function removeCheckboxError(checkbox) {
$(checkbox).parent().next('.error').remove();
}