如何提交附加表格

时间:2016-12-21 13:14:53

标签: javascript jquery html css

每次点击时我都有一个更多按钮来克隆表单。我想用ajax提交每个表单,当每个表单的SUBMIT按钮被点击时。我怎样才能用Ajax方法单独提交每个表单? 这是我的代码:

$(document).ready(function() {
  $(".More").click(function() {
    $(".MyForm")
      .eq(0)
      .clone()
      .show()
      .insertAfter(".MyForm:last");
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.1/jquery.min.js"></script>
<span class="More">More+</span>
<div class="all">
  <form class="MyForm" method="post">
    <input type="text" placeholder="name" value="Aynaz" />
    <select name="Avg">
      <option value="1">1</option>
      <option value="2">2</option>
    </select>
    <button type="submit">Submit</button>
  </form>
</div>

1 个答案:

答案 0 :(得分:1)

在您拥有的每个click按钮上添加submit侦听器,停止默认操作(以确保不提交特定表单),并为每个表单创建新的ajax :

&#13;
&#13;
$(document).ready(function() {
  $(".More").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()
        }
      )
    });
  });
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.1/jquery.min.js"></script>
<span class="More">More+</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>
&#13;
&#13;
&#13;

  

注意 - 我必须在文本输入中添加name属性(没有提交名称的输入)。