Submit form after calling e.preventDefault()
The problem is that, even if you see the error, your return false
affects the callback of the .each()
method ... so, even if there is an error, you reach the line
$('form').unbind('submit').submit();
and the form is submitted.
You should create a variable, validated
, for example, and set it to true. Then, in the callback, instead of return false
, set validated = false
.
Finally...
if (validated) $('form').unbind('submit').submit();
This way, only if there are no errors will the form be submitted.
The simplest solution is just to not call e.preventDefault()
unless validation actually fails. Move that line inside the inner if
statement, and remove the last line of the function with the .unbind().submit()
.
Use the native element.submit()
to circumvent the preventDefault in the jQuery handler, and note that your return statement only returns from the each loop, it does not return from the event handler
$('form').submit(function(e){
e.preventDefault();
var valid = true;
$('[name="atendeename[]"]', this).each(function(index, el){
if ( $(el).val() ) {
var entree = $(el).next('input');
if ( ! entree.val()) {
entree.focus();
valid = false;
}
}
});
if (valid) this.submit();
});
Actually this seems to be the correct way:
$('form').submit(function(e){
//prevent default
e.preventDefault();
//do something here
//continue submitting
e.currentTarget.submit();
});