每次点击时我都有一个更多按钮来克隆表单。我想用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>
答案 0 :(得分:1)
在您拥有的每个click
按钮上添加submit
侦听器,停止默认操作(以确保不提交特定表单),并为每个表单创建新的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()
}
)
});
});
});
&#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;
注意 - 我必须在文本输入中添加
name
属性(没有提交名称的输入)。