How to submit an added form separately

There is a button labeled NEWFORM to create a new form when clicked. Each form has a submit button. When the submit button of each form is pressed, the values โ€‹โ€‹of this form will be sent via AJAX. My code works well for the first time, but when a new form is created and submitted, all the values โ€‹โ€‹of all forms will be submitted together.

Here is my snippet:

$(document).ready(function() { $(".newform").click(function() { $(".MyForm") .eq(0) .clone() .show() .insertAfter(".MyForm:last"); }); $(document).on('click', '.MyForm button[type=submit]', function(e) { e.preventDefault() // To make sure the form is not submitted $('.MyForm').each(function() { console.log($(this).serialize()) $.ajax( $(this).attr('action'), { method: $(this).attr('method'), data: $(this).serialize() } ) }); }); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.1/jquery.min.js"></script> <span class="newform">NEWFORM+</span> <div class="all"> <form class="MyForm" method="post"> <input type="text" placeholder="name" value="Aynaz" name="a1" /> <select name="Avg"> <option value="1">1</option> <option value="2">2</option> </select> <button type="submit">Submit</button> </form> </div> 
+5
source share
3 answers

You repeat all the ".MyForm" objects in your solution, so they are all presented, you need to first determine the correct form in onClick, and then send:

 $(document).ready(function() { $(".newform").click(function() { $(".MyForm") .eq(0) .clone() .show() .insertAfter(".MyForm:last"); }); $(document).on('click', '.MyForm button[type=submit]', function(e) { e.preventDefault() // To make sure the form is not submitted var $frm = $(this).closest('.MyForm'); console.log($frm.serialize()); $.ajax( $frm.attr('action'), { method: $frm.attr('method'), data: $frm.serialize() } ); }); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.1/jquery.min.js"></script> <span class="newform">NEWFORM+</span> <div class="all"> <form class="MyForm" method="post"> <input type="text" placeholder="name" value="Aynaz" name="a1" /> <select name="Avg"> <option value="1">1</option> <option value="2">2</option> </select> <button type="submit">Submit</button> </form> </div> 
+3
source
  $(document).ready(function() { $(".newform").click(function() { $(".MyForm") .eq(0) .clone() .show() .insertAfter(".MyForm:last"); }); $(document).on('click', '.MyForm button[type=submit]', function(e) { e.preventDefault() // To make sure the form is not submitted var $this = $(this).closest("form"); console.log($this.serialize()) $.ajax( $(this).attr('action'), { method: $this.attr('method'), data: $this.serialize() } ) }); }); 
0
source

You could do it sooner

 $(document ).on('submit', '.myForm', function(e) { e.preventDefault() $.ajax({ type: 'post', data: $(this).serialize(), url: 'submit.php' }) }) 

The problem is your contextual use of $(this)

0
source

Source: https://habr.com/ru/post/1261692/


All Articles