可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
I have a button that I would like to disable when the form submits to prevent the user submitting multiple times.
I have tried naively disabling the button with javascript onclick but then if a client side validation that fails the button remains disabled.
How do I disable the button when the form successfully submits not just when the user clicks?
This is an ASP.NET form so I would like to hook in nicely with the asp.net ajax page lifecycle if possible.
回答1:
Give this a whirl:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Threading;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
// Identify button as a "disabled-when-clicked" button...
WebHelpers.DisableButtonOnClick( buttonTest, "showPleaseWait" );
}
protected void buttonTest_Click( object sender, EventArgs e )
{
// Emulate a server-side process to demo the disabled button during
// postback.
Thread.Sleep( 5000 );
}
}
using System;
using System.Web;
using System.Web.UI.WebControls;
using System.Text;
public class WebHelpers
{
//
// Disable button with no secondary JavaScript function call.
//
public static void DisableButtonOnClick( Button ButtonControl )
{
DisableButtonOnClick( ButtonControl, string.Empty );
}
//
// Disable button with a JavaScript function call.
//
public static void DisableButtonOnClick( Button ButtonControl, string ClientFunction )
{
StringBuilder sb = new StringBuilder( 128 );
// If the page has ASP.NET validators on it, this code ensures the
// page validates before continuing.
sb.Append( "if ( typeof( Page_ClientValidate ) == 'function' ) { " );
sb.Append( "if ( ! Page_ClientValidate() ) { return false; } } " );
// Disable this button.
sb.Append( "this.disabled = true;" );
// If a secondary JavaScript function has been provided, and if it can be found,
// call it. Note the name of the JavaScript function to call should be passed without
// parens.
if ( ! String.IsNullOrEmpty( ClientFunction ) )
{
sb.AppendFormat( "if ( typeof( {0} ) == 'function' ) {{ {0}() }};", ClientFunction );
}
// GetPostBackEventReference() obtains a reference to a client-side script function
// that causes the server to post back to the page (ie this causes the server-side part
// of the "click" to be performed).
sb.Append( ButtonControl.Page.ClientScript.GetPostBackEventReference( ButtonControl ) + ";" );
// Add the JavaScript created a code to be executed when the button is clicked.
ButtonControl.Attributes.Add( "onclick", sb.ToString() );
}
}
回答2:
I'm not a huge fan of writing all that javascript in the code-behind. Here is what my final solution looks like.
Button:
<asp:Button ID="btnSubmit" runat="server" Text="Submit" OnClick="btnSubmit_Click" OnClientClick="doSubmit(this)" />
Javascript:
<script type="text/javascript"><!--
function doSubmit(btnSubmit) {
if (typeof(Page_ClientValidate) == 'function' && Page_ClientValidate() == false) {
return false;
}
btnSubmit.disabled = 'disabled';
btnSubmit.value = 'Processing. This may take several minutes...';
<%= ClientScript.GetPostBackEventReference(btnSubmit, string.Empty) %>;
}
//-->
</script>
回答3:
The following function is useful without needing the disabling part which tends to be unreliable. Just use "return check_submit();" as part of the onclick handler of the submit buttons.
There should also be a hidden field to hold the form_submitted initial value of 0;
<input type="hidden" name="form_submitted" value="0">
function check_submit (){
if (document.Form1.form_submitted.value == 1){
alert("Don't submit twice. Please wait.");
return false;
}
else{
document.Form1.form_submitted.value = 1;
return true;
}
return false;
}
回答4:
Disable the button at the very end of your submit handler. If the validation fails, it should return false before that.
However, the JavaScript approach is not something that can be relied upon, so you should have something to detect duplicates on the server as well.
回答5:
if the validation is successful, then disable the button. if it's not, then don't.
function validate(form) {
// perform validation here
if (isValid) {
form.mySubmitButton.disabled = true;
return true;
} else {
return false;
}
}
<form onsubmit="return validate(this);">...</form>
回答6:
Set the visibility on the button to 'none';
btnSubmit.Attributes("onClick") = document.getElementById('btnName').style.display = 'none';
Not only does it prevent the double submission, but it is a clear indicator to the user that you don't want the button pressed more than once.
回答7:
Not sure if this will help, but there's onsubmit event in form. You can use this event whenever the form submit (from any button or controls).
For reference: http://www.htmlcodetutorial.com/forms/_FORM_onSubmit.html
回答8:
A solution will be to set a hidden field when the button is clicked, with the number 1.
On the button click handler first thing is to check that number if it is something other than 1 just return out of the function.
回答9:
You may also be able to take advantage of the onsubmit() javascript event that is available on forms. This event fires when the form is actually submit and shouldn't trap until after the validation is complete.
回答10:
This is an easier but similar method than what rp has suggested:
function submit(button) {
Page_ClientValidate();
if(Page_IsValid)
{
button.disabled = true;
}
}
<asp:Button runat="server" ID="btnSubmit" OnClick="btnSubmit_OnClick" OnClientClick="submit(this)" Text="Submit Me" />
回答11:
Note that rp's approach will double submit your form if you are using buttons with UseSubmitBehavior="false"
.
I use the following variation of rp's code:
public static void DisableButtonOnClick(Button button, string clientFunction)
{
// If the page has ASP.NET validators on it, this code ensures the
// page validates before continuing.
string script = "if (typeof(Page_ClientValidate) == 'function') { "
+ "if (!Page_ClientValidate()) { return false; } } ";
// disable the button
script += "this.disabled = true; ";
// If a secondary JavaScript function has been provided, and if it can be found, call it.
// Note the name of the JavaScript function to call should be passed without parens.
if (!string.IsNullOrEmpty(clientFunction))
script += string.Format("if (typeof({0}) == 'function') {{ {0}() }} ", clientFunction);
// only need to post back if button is using submit behaviour
if (button.UseSubmitBehavior)
script += button.Page.GetPostBackEventReference(button) + "; ";
button.Attributes.Add("onclick", script);
}
回答12:
The correct (as far as user-friendliness is concerned, at least) way would be to disable the button using the OnClientClick attribute, perform the client-side validation, and then use the result of that to continue or re-enable the button.
Of course, you should ALSO write server-side code for this, as you cannot rely on the validation even being carried out due to a lack, or particular implementation, of JavaScript. However, if you rely on the server controlling the button's enabled / disabled state, then you basically have no way of blocking the user submitting the form multiple times anyway. For this reason you should have some kind of logic to detect multiple submissions from the same user in a short time period (identical values from the same Session, for example).
回答13:
one of my solution is as follow:
add the script in the page_load of your aspx file
HtmlGenericControl includeMyJava = new HtmlGenericControl("script");
includeMyJava.Attributes.Add("type", "text/javascript");
includeMyJava.InnerHtml = "\nfunction dsbButton(button) {";
includeMyJava.InnerHtml += "\nPage_ClientValidate();";
includeMyJava.InnerHtml += "\nif(Page_IsValid)";
includeMyJava.InnerHtml += "\n{";
includeMyJava.InnerHtml += "\nbutton.disabled = true;";
includeMyJava.InnerHtml += "}";
includeMyJava.InnerHtml += "\n}";
this.Page.Header.Controls.Add(includeMyJava);
and then set your aspx button parameters as follow:
<asp:Button ID="send" runat="server" UseSubmitBehavior="false" OnClientClick="dsbButton(this);" Text="Send" OnClick="send_Click" />
Note that "onClientClick" helps to disable to button and "UseSubmitBehaviour" disables the traditional submitting behaviour of page and allows asp.net to render the submit behaviour upon user script.
good luck
-Waqas Aslam
回答14:
Just heard about the "DisableOnSubmit" property of an <asp:Button>, like so:
<asp:Button ID="submit" runat="server" Text="Save"
OnClick="yourClickEvent" DisableOnSubmit="true" />
When rendered, the button's onclick attribute looks like so:
onclick="this.disabled=true; setTimeout('enableBack()', 3000);
WebForm_DoPostBackWithOptions(new
WebForm_PostBackOptions('yourControlsName', '', true, '', '', false, true))
And the "enableBack()' javascript function looks like this:
function enableBack()
{
document.getElementById('yourControlsName').disabled=false;
}
So when the button is clicked, it becomes disabled for 3 seconds. If the form posts successfully then you never see the button re-enable. If, however, any validators fail then the button becomes enabled again after 3 seconds.
All this just by setting an attribute on the button--no javascript code needs to be written by hand.
回答15:
So simply disabling the button via javascript is not a cross-browser compatible option. Chrome will not submit the form if you just use OnClientClick="this.disabled=true;"
Below is a solution that I have tested in Firefox 9, Internet Explorer 9, and Chrome 16:
<script type="text/javascript">
var buttonToDisable;
function disableButton(sender)
{
buttonToDisable=sender;
setTimeout('if(Page_IsValid==true)buttonToDisable.disabled=true;', 10);
}
</script>
Then register 'disableButton' with the click event of your form submission button, one way being:
<asp:Button runat="server" ID="btnSubmit" Text="Submit" OnClientClick="disableButton(this);" />
Worth noting that this gets around your issue of the button being disabled if client side validation fails. Also requires no server side processing.
回答16:
Building on @rp.'s answer, I modified it to invoke the custom function and either submit and disable on success or "halt" on error:
public static void DisableButtonOnClick(Button ButtonControl, string ClientFunction)
{
StringBuilder sb = new StringBuilder(128);
if (!String.IsNullOrEmpty(ClientFunction))
{
sb.AppendFormat("if (typeof({0}) == 'function') {{ if ({0}()) {{ {1}; this.disabled=true; return true; }} else {{ return false; }} }};", ClientFunction, ButtonControl.Page.ClientScript.GetPostBackEventReference(ButtonControl, null));
}
else
{
sb.Append("return true;");
}
ButtonControl.Attributes.Add("onclick", sb.ToString());
}
回答17:
Came across rp's code in a legacy app of ours which was struggling with some crazy behaviour.
Tracked it down to a strange combination of event firing - when DisableButtonOnClick() was being used on an asp button inside an UpdatePanel, the POST would be sent twice (once by the doPostBack added by DisableButtonOnClick(), and once by the UpdatePanel). However, this only happened with some browsers (early versions of Edge, but not recent ones, and IE11 did this, Chrome and FireFox did not (at least the versions I tested with)). I presume Chrome and newer versions of Edge are dealing with this scenario internally in some way. Tracking the issue with F12 devtools in IE - the two POSTs happen so closely together that the first one gets immediately ABORTED, but under some conditions (network latency, user machine load, etc) the request does get through to the server before the browser can abort. So this results in a seemingly random double-post coming from button presses throughout the system, and it was a pain to trace back. The fix is to add a "return false;" after the doPostBack to prevent the UpdatePanel from getting involved when older browsers are in play.
TLDR - beware of this code on buttons in updatepanels. It's a good approach and nice method but has a potential issue in my (likely edge) case.
ps - I would have commented on rp's post but I don't have the rep. Thought it might be useful for future travelers.