Wesley Murch Wesley Murch - 11 months ago 63
jQuery Question

Submit form after calling e.preventDefault()

I'm doing some simple form validation here and got stuck on a very basic issue. I have 5 field pairs for name and entree (for a dinner registration). The user can enter 1-5 pairs, but an entree must be selected if a name is present. Code:

http://jsfiddle.net/eecTN/1/

<form>
Name: <input name="atendeename[]">
Entree: <input name="entree[]"><br>
Name: <input name="atendeename[]">
Entree: <input name="entree[]"><br>
Name: <input name="atendeename[]">
Entree: <input name="entree[]"><br>
Name: <input name="atendeename[]">
Entree: <input name="entree[]"><br>
Name: <input name="atendeename[]">
Entree: <input name="entree[]"><br>
<input type="submit" value="Submit">
</form>




// Prevent form submit if any entrees are missing
$('form').submit(function(e){

e.preventDefault();

// Cycle through each Attendee Name
$('[name="atendeename[]"]', this).each(function(index, el){

// If there is a value
if ($(el).val()) {

// Find adjacent entree input
var entree = $(el).next('input');

// If entree is empty, don't submit form
if ( ! entree.val()) {
alert('Please select an entree');
entree.focus();
return false;
}
}
});

$('form').unbind('submit').submit();

});


The error message is working, but it's submitting the form every time. I know there's something wrong with this line:

$('form').unbind('submit').submit();


...but I'm not sure what I need to do.

Answer Source

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().

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download