tags:

views:

7826

answers:

4

Hello! 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!

+17  A: 

You can select the form like this:

$("#submit").click(function(){
    var form = $(this).parents('form:first');
    ...
});

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:

$('form#myform1').submit(function(e){
     e.preventDefault(); //Prevent the normal submission action
     var form = this;
     // ... Handle form submission
});

To select fields inside the form, use the form context. For example:

$("input[name='somename']",form).val();
Eran Galperin
You could also use to select all the input children: $(this).children().filter("input")
Pim Jager
or $("input,textarea,select",form)
Eran Galperin
A: 

(AH!!! Thank you, I have been wondering about that click vs submit thing, and that is the first explanation I've read that makes sense. )

So I declare "form". Then do I say "var nameVal = form.inputname.val(); "? Or should I use the input id?

EDIT: (Hey, you answered while I was asking. Thanks!)

A: 

to get the form that the submit is inside why not just this.form Easiest & quickest path to the result

redsquare
A: 

Eileen: no, it is not "var nameVal = form.inputname.val();" it should be either...

in Jquery:

//you can use ids (easier)

var nameVal =  $(form).find('#id').val();

//or use the [name=Fieldname] to search for the field

var nameVal =  $(form).find('[name=Fieldname]').val();

Or in Javascript:

var nameVal = this.form.FieldName.value;

Or a combination: var nameVal = $(this.form.FieldName).val();

With Jquery, you could even loop through all of the inputs in the form:

$(form).find('input, select, textarea').each(function(){

  var name = this.name;
  // OR
  var name = $(this).attr('name');

  var value = this.value;
  // OR
  var value = $(this).val();
  ....
  });
Lathan