我有一个页面可以根据数据库中的行动态创建表单。每个表行都包含一个带有提交按钮的表单,用于从数据库中删除记录。我似乎无法弄清楚如何选择当前表单进行提交。它们都有不同的ID,但是脚本如何知道用户点击的形式?
<form name="myForm" id="1">
<input type="hidden" name="id" value="1">
<input type="hidden" name="table" value="sales">
<button name="command" type="submit" class="btn btn-danger" title="Delete">
<i class="fe fe-trash-2"></i></button>
</form>
<form name="myForm" id="2">
<input type="hidden" name="id" value="2">
<input type="hidden" name="table" value="sales">
<button name="command" type="submit" class="btn btn-danger" title="Delete">
<i class="fe fe-trash-2"></i></button>
</form>
$('input[type="submit"]').click(function(){
var thisForm = this.form;
$.ajax({
url: "delete_do.php",
method: "POST",
data: $(thisForm).serialize(),
});
});
答案 0 :(得分:1)
请查看下面的代码段。请注意,由于存在名为id
,form.id
或this.id
的字段,因此不会提供表单id
的值。因此$('form').attr('id')
。
$(function() {
$('form[name="myForm"]').on('submit', function(e) {
e.preventDefault();
//form ID ** cannot use form.id or this.id
//because you've named a field id .. name="id" **
var formID = $(this).attr('id');
console.log( formID );
//form Data
console.log( $(this).serialize() ); //or
console.log( $(this).serializeArray() );
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form name="myForm" id="1">
<input type="hidden" name="id" value="1">
<input type="hidden" name="table" value="sales">
<button name="command" type="submit" class="btn btn-danger" title="Delete">
<i class="fe fe-trash-2"></i></button>
</form>
<form name="myForm" id="2">
<input type="hidden" name="id" value="2">
<input type="hidden" name="table" value="sales">
<button name="command" type="submit" class="btn btn-danger" title="Delete">
<i class="fe fe-trash-2"></i></button>
</form>