gpt4 book ai didi

javascript - 如何提交附加表格

转载 作者:行者123 更新时间:2023-11-28 17:23:38 25 4
gpt4 key购买 nike

每次单击时我都有一个“更多”按钮来克隆表单。我想在单击每个表单的“提交”按钮时使用 ajax 提交每个表单。如何使用 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>

最佳答案

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

$(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()
}
)
});
});
});
<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>

Note - i had to add a name attribute to your text input (inputs without names are not being submitted).

关于javascript - 如何提交附加表格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41263650/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com