views:

62

answers:

2

Hi,

I have a page that contains several forms that are identical throughout a page. I submit these forms using the $.ajax() method.

As I see it using classes to identify/submit/validate the individual forms will likely be problematic. Passing the form with something like $('.someForms').serialize() would not produce viable results. How would .serialize() select the proper form??

Even if .serialize() would work, I'm not sure how to go about applying any form validation suggestions to specific fields...

The other option I see is to code for each form.

Ex: $('#thisForm').serialize();

I'm curious how you jQuery guru's handle multiple forms like this?

+2  A: 

There are many ways to select forms. You could select them by their index:

$("form:eq(0)").serialize(); // serialize first form on page
$("form:eq(3)").serialize(); // serialize fourth form on page

You could select them by first going through a unique child of theirs:

$(":input[name='uniqueChild']").closest("form").serialize(); // serialize holder

You could select them by channeling through a unique parent of theirs:

$("#userDetails form").serialize(); // serialize form within DIV#userDetails

While there are many other ways to access forms specifically, I must say that if you find yourself needing to use any of these aforementioned methods, you probably need to rethink your code a bit.

Jonathan Sampson
thanks! I had a feeling it could be done easily...
Derek Adair
+1  A: 

One of the tags on this question was "validation". Does that mean you are using jquery's validation before submitting the forms?

If you are, then the "submitHandler" option on validate will pass in the form object to the handler function. You should be able to avoid searching for which element is being submitted through that callback.

$('form').validate({
     ...

     submitHandler: function(form) {
         $.ajax(
              url,
              $(form).serialize(),
              ...
         );
     },

     ...
});
smaglio81
cool. I plan on implementing the jQuery form handler, I haven't got a chance yet.
Derek Adair