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.
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…