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.
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).
Definition and Usage. The preventDefault() method cancels the event if it is cancelable, meaning that the default action that belongs to the event will not occur. For example, this can be useful when: Clicking on a "Submit" button, prevent it from submitting a form.
preventDefault() method stops the default action of an element from happening. For example: Prevent a submit button from submitting a form. Prevent a link from following the URL.
The HTML DOM Form submit() method is used for submitting the form data to the address specified by the action attribute. It acts as a submit button to submit form data and it doesn't take any kind of parameters.
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()
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With