I have a web page with 3 forms on it. Not nested, just one after the other (they are almost identical, just one hidden variable that’s different). A user will only fill in one form, and I’d like to validate/etc all the forms with only one JS script.
So how, when a user clicks the submit button of form#1, do I make my js script only deal with the fields in form1? I gather it has something to do with $(this).parents , but I am not sure what to do with it.
My validation script (which I used elsewhere, with only a single form) looks something like so:
$(document).ready(function(){ $('#submit').click(function(){ $('.error').hide(); var hasError = false; var nameVal = $('#name').val(); if(nameVal == '') { $('#name').after('Please enter your name.'); hasError = true; } if(hasError == false) {blah blah do all the processing stuff}
So do I need to replace things like $(‘#name’).val() with $(this).parents(‘form’).name.val() ? Or is there a better way to go about this?
Thanks!
You can select the form like this:
However, it is generally better to attach the event to the submit event of the form itself, as it will trigger even when submitting by pressing the enter key from one of the fields:
To select fields inside the form, use the form context. For example: