[英]Disabling forms with javascript on submit to prevent double submit
I'd like to disable a form after it is submitted in order to prevent double submissions. 我想在表单提交后将其禁用,以防止重复提交。 Pretty standard use case I would think, but all of the examples I can find out there are flawed. 我认为这是非常标准的用例,但是我可以发现那里的所有示例都是有缺陷的。
Everything I can find is based on disabling the submit button, but this doesn't prevent the form from being re-submitted if the user hits the enter key on the form, which is a pretty common approach. 我能找到的所有内容都是基于禁用“提交”按钮的,但这并不能防止如果用户单击表单上的Enter键,则无法重新提交表单,这是一种非常常见的方法。
I'm thinking about modifying one of the existing scripts out there to account for this, but before I reinvent the wheel, does anyone know of a script that already handles this properly that they're able to share? 我正在考虑修改现有的脚本之一以解决此问题,但是在我重新发明轮子之前,是否有人知道一个可以正确处理并可以共享的脚本? I'm really surprised there doesn't seem to be anything out there yet. 我真的很惊讶,似乎还没有任何东西。
You could create a boolean variable (or an object with a boolean member variable) and only submit the form when the variable is false. 您可以创建一个布尔变量(或具有布尔成员变量的对象),并且仅在变量为false时才提交表单。 Something like: 就像是:
function init() {
var submit = false;
var f = document.getElementById("FormID");
f.onsubmit = function() {
if(submit) {
return false;
} else {
submit = true;
return true;
}
}
}
Of course, you would have to call init
following the page load, in whichever flavor you choose to do that ( window.onload = ...
, window.addEventListener(...)
, window.attachEvent(...)
, etc.). 当然,您必须在页面加载后调用init
,无论选择哪种方式( window.onload = ...
, window.addEventListener(...)
, window.attachEvent(...)
等)。
http://jsfiddle.net/c2N4v/ http://jsfiddle.net/c2N4v/
var sent = false;
$('#form').submit(function(e) {
if (!sent) {
sent = true;
// do whatever
}
else e.preventDefault();
});
i've tried a lot of solutions but none of them worked for me. 我尝试了很多解决方案,但没有一个对我有用。 I used this one and it is working really fine: 我用了这个,它真的很好用:
jQuery jQuery的
<script>
$(document).ready(function(){
$('#buttonSubmit').click(function() {
if ($('#frm-confirm').attr('submitted')){
event.preventDefault();
} else {
$('#frm-confirm').attr('submitted',true);
}
});
});
</script>
HTML/PHP HTML / PHP
<form id="frm-confirm" action="" method="post">
<input id="amount" name="amount" value="<?php echo round($_POST['amount'],2); ?>" type="hidden" />
<input id="order_id" name="order_id" value="<?php echo htmlspecialchars($_POST['order_id']);?>" type="hidden" />
<input type="submit" id="buttonSubmit" name="confirm" value="Confirm" />
</form>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.