tags:

views:

578

answers:

4

I am using this plugin: http://malsup.com/jquery/form/#getting-started

I am having issues, getting it to submit (using a single function) more than one form on the page at the same time, and to make it more complicated, I am loading the form via ajax from a remote html call. So the form function needs to be loaded again.

The question is how to use (if possible) a re-usable function that can submit multiple forms at the same time.

A: 

The jQuery plugin add an event listener to the onsubmit event of the form(s) you specify. So in order to submit multiple forms at the same time you'll need a function that invokes the submit events of each form. Something like this:

function doubleSubmit(e) {
 if (e.target.id == 'form2') {
   $('#form1').submit();
  } else {
   $('#form2').submit();
  }
}

The next trick is to have this function be called when either form submits. I would do something like this:

$("#form1").bind("submit", doubleSubmit);
$("#form2").bind("submit", doubleSubmit);

I haven't tested this code, but it should give you the general idea.

macinjosh
I'm not convinced this will work. Won't this just submit 'the other' form, since one postback will occur, cancelling the other?
David Archer
A: 

You can't submit multiple forms at once. But you could submit them sequentially

function submitFn() {
$('form').each(function() {
$.post(url, data, function() {
... 

 }
return false;
});}

and add listeners:

$('form').bind('submit', submitFn);

The return false is important coz if you don't have it then the first form submitted will submit twice

David Archer
A: 

Id probably go for something like this:

// after you import the html
$("#form1, #form2").bind("submit", submit);
// or simply
$("form").bind("submit", submit);

function submit() {
  /// a $.post implementation selecting all the controls and passing them as data
  return false; // to prevent an actual browser submit
}
Fabian
+2  A: 

May be you can use LiveQuery Plugin for that problem. It could work like for example

<button ... rel="formId"/>
jQuery(".formButton").livequery("click",function() {
  var formId=jQuery(this).attr("rel");
  jQuery("#"+formId).ajaxSubmit();
}

So button with class .formButton can be included in server response and with livequery it is also be handled. Hope it helps. Sorry for my English.

Alexey Ogarkov
Note for anyone reading this answer ... jQuery now has a $.live() function that binds an event listener to dynamic DOM nodes. No need for a plugin to do this.
b. e. hollenbeck