表单多次提交多次点击按钮



我正在尝试通过使用 AJAX 提交表单来创建异常,并且在按钮时也会创建异常

<button type="button" onclick="submitForm()" class="btn btn-s-md btn-primary saveButton mb-10 "><i class="fa fa-save fa-fw"></i>Save</button>

单击,然后单击执行function submitForm()函数。

问题是多次单击按钮时,表单也会提交,这是我不想要的。

以下是我的表格

<form asp-action="CreateException" asp-controller="Attorney" method="post" role="form" enctype="multipart/form-data" id="attorneyExceptionForm">
<div class="panel panel-default">
<div class="panel-body">
<div class="row">
<div class="col-md-3 col-lg-3 col-sm-12">
<div class="form-group">
<label asp-for="Description" class="control-label ">Description<span class="requAstrik">*</span></label>
<input asp-for="Description" class="form-control " />
<span asp-validation-for="Description" class="text-danger"></span>
</div>
</div>
<div class="col-md-3 col-lg-3 col-sm-12">
<div class="form-group">
<label asp-for="Exception" class="control-label ">Exception<span class="requAstrik">*</span></label>
<select id="slctExceptionA" class="form-control select2" asp-for="Exception" style="color: #444 !important;width:100%;" asp-items="@(new SelectList(@ViewBag.ExcsList, "ExcId", "ExcDescription" ))"></select>
<span id="attorneyExceptionError" asp-validation-for="Exception" class="text-danger"></span>
</div>
</div>                       
</div>                   
</div>
</div>           
<div class="form-group">
<button type="button" onclick="submitForm()" class="btn btn-s-md btn-primary saveButton mb-10 "><i class="fa fa-save fa-fw"></i>Save</button>
</div>
</form>

下面是我的js函数

<script>
function submitForm() {
debugger;
var datastring = $("#attorneyExceptionForm").serialize();
var validForm = $("#attorneyExceptionForm").valid();
if (!validForm) { return false; }
$.ajax({
type: "POST",
url: "/Attorney/CreateAttorneyException",
data: datastring,
dataType: "json", 
success: function (data) {
debugger;
if (data.success.Result) {
debugger;
$("#myModal5").modal('hide');
var grid = $("#AttorneyExceptionGrid").dxDataGrid('instance');
grid.refresh();
showNotification("Exception saved successfully", "success");
}
else {
debugger;
showNotification(data.success.MessageBody + " is required ", "warning");
}
},
error: function (data) {
debugger;
showNotification("Please input the required field", "warning");
}
});
}
</script>

您可以在第一次单击时禁用该按钮,并在 ajax 响应到达时再次启用它。

<button type="button" onclick="submitForm(this)" class="btn btn-s-md btn-primary saveButton mb-10 "><i class="fa fa-save fa-fw"></i>Save</button>
function submitForm(e) {
$(e).prop("disabled", true);
//more code
}

并在成功或错误 ajax 方法中再次启用它

$(e).prop("disabled", false);

最新更新