Merge two or multiple HTML Forms with jQuery

Technik

While it is not the most beautiful method of submitting forms, sometimes you may need to combine two forms and submit them jointly. Unfortunately this is nothing your browser can do by it self, you'll need jQuery and a few lines of code.

In my case, I had some input fields in the main area of the page and a few additional input fields in the sidebar. Creating a large form-tag that covers both would have had quite an impact on the structure of my site. So I thought of simply combining two forms.

<script>
$('form.mfsubmit').submit(function(event){
  // parsley validate
  var valid = true;
  $('form.mfsubmit').each(function(i){
    if(!$('form.mfsubmit').eq(i).parsley().validate())
      valid = false;
  });
  
  if(valid){
    // combine all forms with the class mfsubmit
    var mfform = $(document.createElement('form'));
    
    $('form.mfsubmit').find('select, textarea').each(function(i, e){
      var prop = $(e).prop('tagName').toLowerCase();
      if(prop == 'textarea' && $(e).hasClass('tinymce'))
        mfform.append($(document.createElement(prop)).attr('name', $(e).attr('name')).val(tinymce.get($(e).attr('name')).getContent()));
      else
        mfform.append($(document.createElement(prop)).attr('name', $(e).attr('name')).val($(e).val()));
    });
    
    mfform.append($('form.mfsubmit').find('input').clone());
    
    mfform.attr({ action: $(this).attr('action').substr(1), method: 'post' })
      .hide()
      .appendTo('body')
      .submit();
      
  }
  
  // prevent default submission
  event.preventDefault();
  return false;
});
</script>

Just add the class mfsubmit to your form-tags. This script, when included with jQuery, will then create a new form and append all input, select and textarea fields to this form. While input fields can simply be copied with the jQuery .clone() function, select and textarea fields need some extra treatment.

The first few lines will validate your input fields using parsley.js. If you are not using any validation or an other software, feel free to remove or modify the code.

In case you use tinyMCE, this script also pastes the content from the editor to the textarea. Just add the class tinymce to all your tinyMCE textareas.

Attention: In order to prevent false submitting, I'm adding a # to the beginning of the destination page. E.g:

<form action="#/some/destination/" method="post">

This character will be removed, when submitting the form. However, if the form is removed without JavaScript, nothing will happen. If you do not want this behavior, just remove the substr(1) part from the code above.

Feel free to modify and share this code, just don't forget to add a link.

Permalink: https://to.ptmr.io/1zpYDMN