I have a form where the input boxes are prefilled with default values. A jQuery event handler clears the value on 'focus' and restores the default value on 'blur', if the field is empty.
$('form input').on('focus blur', function (event) {
var eventTarget = $(this);
if (eventTarget.val() === eventTarget.data('default')
|| eventTarget.val() === '') {
if (event.type === 'focus') {
eventTarget.val('').removeClass('empty');
} else {
eventTarget.val(eventTarget.data('default')).addClass('empty');
}
}
}).trigger('blur');
Before submitting (via AJAX), I empty all fields that contain the default value and trigger client side validation (for required fields):
$('form').on('submit', function (e) {
$('form input').each(function () {
if ($(this).val() === $(this).data('default')) {
$(this).val(''); // remove default value, so 'required' validation triggers on empty fields
}
});
if ($('form').valid()) {
$.ajax(...);
} else {
$('form input').trigger('blur'); // trigger 'blur' to restore default values
// Problem: This clears the validation messages
}
});
So far, so good, however after that, my form fields are of course empty. If I trigger the 'blur' event again, I can restore the default values, but that makes the validation messages disappear, probably because client side validation runs again and sees that the fields are no longer empty.
When I manually click in and out of the form field, though, the default value is restored and the validation message stays. Both go through the same 'blur' handler. I cannot figure out where the difference is.
Edit: I have since figured out that I can disable validation on 'blur' completely:
$('form').validate().settings.onfocusout = false;
This works around my issue for now, but I would still like to know why blur/focusout reacts differently when triggered from a script or from user interaction.