Home > Net >  How do I add forms together in jQuery?
How do I add forms together in jQuery?

Time:08-25

I am creating a form that has multiple sections. I want to add each of these to a "finalsubmit" form. How can I add the entire section forms to the final one?

 <form id='1'  name='1' method='POTS' action='#'>
    <input type='text' id='blah' name='blah'>
    <input type='text' id='blahblah' name='blahblah'>
    <input type='button' id='sub1' value='Submit'>
</form>
<form id='2' class='section' name='2' method='POST' action='#'>
    <input type='text' id='blah2' name='blah2'>
    <input type='text' id='blahblah2' name='blahblah2'>
    <input type='button' id='sub2' value='Submit'>
</form>


<form id='finalForm' name='finalForm' method='POST' action='#'>
</form>

jQuery (in laymen's terms)

$('#sub1 #sub2').click(function(){
     //Grab all the data from clicked form and add it to $('#finalForm');
 });

CodePudding user response:

Use appendTo() to append the form contents to the other form.

$("form#1, form#2").children().appendTo("#finalForm");

CodePudding user response:

It depents how your final form should look like. If it exists of the inputs from form 1 and form 2 then I would recommend you the way Barmar already posted, otherwise you prevent the submit of both forms and then you get the values of the input fields.

<form id='firstForm' name='1' method='POST'>
      <input type='text' id='blah' name='blah'>
      <input type='text' id='blahblah' name='blahblah'>
      <input type="submit" id="sub1">
   </form>

   <form id='2' class='section' name='2' method='POST' action='#'>
      <input type='text' id='blah2' name='blah2'>
      <input type='text' id='blahblah2' name='blahblah2'>
      <input type='button' id='sub2' value='Submit'>
   </form>


   <form id='finalForm' name='finalForm' method='POST' action='#'>
   </form>

   <script>

      $("form").submit(function (event) {
         event.preventDefault();

         // Input Fields from first form
         const blah = $('#blah').val();
         const blahblah = $('#blahblah').val();

         // Input Fields from second form
         const blah2 = $('#blah2').val();
         const blahblah2 = $('#blahblah2').val();

         // Insert the data into your final form
         
         // Write the inputs in your static html

         // Or you create new Inputs with jQuery
         var exampleInput = $("<input>");
         exampleInput.innerHTML = "Text.";
         $("#finalForm").append(exampleInput);
      });

   </script>
  • Related