Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Merge values from two forms on submit

Tags:

html

jquery

I have two forms on one html page. Using jQuery, is it possible to have the data from both forms go into the POST data when the first is submitted?

like image 210
Brian Avatar asked Feb 26 '10 10:02

Brian


Video Answer


2 Answers

jQuery serialize supports multiple form elements, So it is possible to do:

$('#form1, #form2').serialize(); 

And for your case, you can do:

$('#form1').submit(function() {     var action = $(this).attr('action');     if (!EntryCheck()) return false;     $.ajax({         url  : action,         type : 'POST',         data : $('#form1, #form2').serialize(),         success : function() {             window.location.replace(action);         }     });     return false; }); 
like image 86
Sagi Avatar answered Sep 28 '22 11:09

Sagi


One approach is to copy all of form2's inputs into form1 once the data validation check succeeds. This assumes you are not doing an AJAX submit.

// new onsubmit function for form1 function form1_onsubmit() {     if (!EntryCheck()) return false;       $('#form2 :input').not(':submit').clone().hide().appendTo('#form1');      return true; } 

If you wanted to cater for hitting submit twice, possibly because of submit fail from the server, we would need to remove any copied inputs before copying in new ones.

// new onsubmit function for form1 function form1_onsubmit() {     $('#form1 :input[isacopy]').remove();      if (!EntryCheck()) return false;       $('#form2 :input').not(':submit').clone().hide().attr('isacopy','y').appendTo('#form1');      return true; } 
like image 25
Lachlan Roche Avatar answered Sep 28 '22 11:09

Lachlan Roche