我正在使用jquery submit()函数提交表单,但它多次提交。我用尽了我所知道的一切,但无法阻止它。下面是我的功能:
function submit(){
$("#save").prop('disabled', true);
$("#loader").modal('show');
$("#save").off('click');
if($("#name").val() == ''){
alert("Please Enter Name!");
$("#save").prop('disabled', false);
$("#save").on('click', submit);
$("#loader").modal('hide');
return false;
}
// Other validations as well
$("#form").submit();
}
$("#save").off('click').on('click', submit);
下面是我的表格:
<form action="abc.php" method="post" id="form">
<input type="text" id="name" />
<button type="button" id="save">save</button>
</form>
但有时如果用户多次点击按钮的速度太快,则点击多次工作。不是每次。有人知道吗?
想到的一个选项是在单击时向“Save”按钮添加一个类名,并在回调中检查这个类名,如果类存在,则返回,否则提交。如下所示:
function submit(){
const $saveBtn = $('#save');
//if the button has been clicked already, return
if($saveBtn.hasClass('clicked'){
return;
}else{ //add the class to prevent multiple submission
$saveBtn.addClass('clicked');
}
$saveBtn.prop('disabled', true);
.......
}
编辑
既然您说上面添加className的解决方案不起作用,那么就使用全局布尔值:
在脚本的顶部声明boolean:
let submitted = false;
function submit(){
//if the boolean is true, return
if(submitted){
return;
}else{ //set to true
submitted = true;
}
const $saveBtn = $('#save');
$saveBtn.prop('disabled', true);
.......
}