Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Submit appended 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 clicked, the values of that form will be sent via AJAX. My code works well the first time, but when a new form is created and submitted, all of the values of all forms will send 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>
like image 591
inaz Avatar asked Oct 17 '22 20:10

inaz


1 Answers

You iterate all ".MyForm" objects in your solution, so all of them submitted, you need to determine correct form in onClick first, and then submit it:

$(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>
like image 126
2oppin Avatar answered Oct 20 '22 09:10

2oppin