I have a web form for which I want to prevent multiple submissions. In pr开发者_JAVA技巧oduction, this is accomplished by the submit button having an onclick="this.disabled=true"
attribute. This way, if the form is submitted and then the user goes back (presumably to "edit" the data, which our users seemed to want to do from time to time), the submit button remains disabled.
This works fine in Firefox, Safari, and Internet Explorer. In Chrome, however, the disable seems to fire before the form submission, thus preventing it from happening. In order to work around this, I changed the button's onclick
action to:
this.disabled=true; $('myform').submit()
This results in the form being submitted, but when I use Chrome's back button to return to the form page, the button is no longer disabled. Values I entered into the form before submitting remain, so my guess is that Chrome must be selectively reloading the DOM.
Is there any way to accomplish what I want with Javascript in Chrome? There are other ways to solve this problem, of course, but disabling the button has a highly attractive simplicity to it.
I've tested in Chrome 12.0.742.100 in Linux, and 12.0.742.112 in MacOS X.
I prefer this
http://jsfiddle.net/mplungjan/sCgZ9/
Script:
$("form").submit(function() {
$("#subbut").hide();
$("#submitted").show();
});
CSS:
#submitted { display:none }
HTML:
<form action="http://www.google.com/" target="_blank">
<input type="submit" id="subbut" /><span id="submitted">Form submitted</span>
</form>
You can set a cookie if you want to decide to show or not show the button
Consider instead using the form's submit to disable the button.
In any case, you sould be dealing with this at the server, there are other ways to submit a form without using the submit button. Disabling the button will not prevent the user from re-submitting the form.
Using javascript
<form name ="myform" method="POST" action="youractionhere" onSubmit="document.getElementById('submit').disabled=true;">
<input type="submit" name="submit" value="Submit" id="Submit">
</form>
Using jQuery
$("form").each(function() {
$(this).find("button:submit").click(function() {
if($('input[type="submit"]').hasClass("disabled"))
return false;
$('input[type="submit"]').addClass("disabled");
return true;
});
});
I use to do this
html
<form action="/" method="post">
<button type="button" class="submit-form" >Save</button>
</form>
javascript
var button = document.querySelector('.submit-form')
button.addEventListener("click", function(){
this.setAttribute('disabled',true);
var form = this.closest('form')
form.submit();
},false);
jquery
$(document).on("click",".submit-form",function(){
$(this).attr('disabled',true);
$form = $(this).closest('form');
$form.submit();
});
精彩评论