Jquery - 通过一个按钮提交所有表格 [英] Jquery - Submit all forms by one button
本文介绍了Jquery - 通过一个按钮提交所有表格的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
Html:
<form class="allforms" method="POST" action="/auth/myaccount/personal">
<input type="hidden" name="_method" value="PATCH">
...
</form>
<button id="allsubmit" class="btn btn-info">Continue</button>
jquery:
$(document).ready(function(){
$("#allsubmit").click(function(){
$('.allforms').submit();
});
});
我的html代码中有3个表格,如上所示。
我的按钮不在我的任何表格中。
如何为我的所有表单提供一个提交按钮。我尝试了点击功能,但它不起作用。为什么?
I have 3 forms in my html code like above. My button is out of any my forms. How to have one submit button for all my forms. I tried the click function but it doesn't work. Why?
推荐答案
表单提交是同步操作,因此当您提交表单然后立即在页面中提交其他表单时,第一个表单的提交被取消。
Form submission is a synchronous action, so when you submit a form and then immediately submit a different form in your page, the first form's submission is canceled.
您可以做的是确保表单是异步提交的(使用ajax):
What you can do instead is make sure the forms are submitted asynchronous (using ajax):
$(function() {
$("#allsubmit").click(function(){
$('.allforms').each(function(){
valuesToSend = $(this).serialize();
$.ajax($(this).attr('action'),
{
method: $(this).attr('method'),
data: valuesToSend
}
)
});
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form class="allforms" method="POST" action="">
<input type="hidden" name="_method" value="PATCH1">
<input type="submit" />
</form>
<br />
<form class="allforms" method="POST" action="">
<input type="hidden" name="_method" value="PATCH2">
<input type="submit" />
</form>
<br />
<form class="allforms" method="POST" action="">
<input type="hidden" name="_method" value="PATCH3">
<input type="submit" />
</form>
<br />
<button id="allsubmit" class="btn btn-info">Continue</button>
一些注释
A few notes
- 此不会使用包含文件上传的表单(enctype =multipart / form-data)
- 您需要决定在提交完成后要做什么(因为页面中的任何内容都不会更改)。
- 您无法在stackoverflow-snippets中提交表单,所以不要试试这里运行:)
- This will not work with forms that have file-uploading (enctype="multipart/form-data")
- You need to decide what to do after the submission is done (because nothing in the page will change).
- You can't submit forms in stackoverflow-snippets, so don't try to run this here :)
这篇关于Jquery - 通过一个按钮提交所有表格的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文