I searched through the forum for the answer, yet can't seem to find a definite solution to this common problem. I'm sure everyone at least once had a similar problem - a form that takes a while to submit and you want to disable the submit button so that
the user doesn't click it again. In the good ol' days, I used to just have onclick="this.disabled=true;this.form.submit();" attribute on the button. When I tried the same in .NET - it doesn't work.
I have validation controls on the form and if user clicked submit while some fields are invalid, the validation controls display messages in red next to each invalid field (common technique). If I added "this.disabled=true" to the onclick event in .NET,
then first of all, the form never gets submitted - button stays disabled. If I try something like onclick="this.value='Please wait...'" - also doesn't work, because this changes the button text regardless whether form was valid or not. If it had invalid fields,
then validation controls display their messages but the text of the button remains "Please wait..." - confusing to the user because the form looks like it's being submitted, while in fact it's not.
I just can't find a solution to this simple problem! Is there anything on the client side to detect whether form is valid (similar to the server side Page.IsValid) - so you could do something like: onclick="if (this.form.isvalid){this.disabled=true;}" or
onclick="if (this.form.isvalid) {this.value='Please wait';}"
Thank you. I think I even found a shorter solution (I always try to reduce the amount of code). Now in my button's onclick even I just do "if (Page_ClientValidate()){this.style.display='none';}" - I hide the button instead of disabling it (which causes problem
with .NET) and instead show some "Please wait, processing" message. The key turns out to be this "Page_ClientValidate()" function. Let's just hope that Microsoft won't decide to rename this function into something else in version 3.x, like they like to do.
<param name="disabledText">Text to display on button when clicked</param>
/// <param name="aCol">Optional: Collection of controls on page to disable as well (buttons only for now)</param>
///
<param name="customScript">Optional: Custom script to run before disabling the button</param>
dmose. I just spent the last several hours trying to figure out why I was getting a double postback in Firefox and it's because of this auto disable button code!! Does anyone have a solution that works in firefox?
thanx for your solution dmose, works great in .Net 1.1.
Btw i just fixed the double-postback (Firefox) by appending "return false;". It's all :p
Here my method based on your solution :
Public Shared Sub SetButtonOnClickClientCode( _
ByVal button As System.Web.UI.WebControls.Button, _
ByVal clientScriptCode As String _
)
If (button Is Nothing) Then
Throw New ArgumentException("button cannot be null", "button")
End If
If (button.Page Is Nothing) Then
Throw New ApplicationException("the specified button must belong to a page.")
End If
Dim code As String = clientScriptCode
If (code Is Nothing) Then code = String.Empty
code = code.Trim()
If (code.Length > 0 AndAlso Not code.EndsWith(";")) Then
code &= ";"
End If
Dim onClick As String = String.Empty
If (button.CausesValidation AndAlso button.Page.Validators.Count > 0) Then
' Reflectorized from hidden method :
' System.Web.UI.Util.GetClientValidatedPostback
onClick = _
"if (typeof(Page_ClientValidate) != 'function' || Page_ClientValidate()) "
End If
' ends with 'return false;' to bypass any code
' appended to our string later
onClick &= _
"{" & _
code & _
button.Page.GetPostBackEventReference(button) & ";" & _
"}" & _
"return false;"
button.Attributes("onclick") = onClick
End Sub
' Then u can use something like :
SetButtonOnClickClientCode(myButton, "MyJavascriptFunctionToDisableSubmitElements();")
oc1980
Member
44 Points
15 Posts
Disable button on submit to prevent double submission
Dec 22, 2006 10:13 PM|LINK
I searched through the forum for the answer, yet can't seem to find a definite solution to this common problem. I'm sure everyone at least once had a similar problem - a form that takes a while to submit and you want to disable the submit button so that the user doesn't click it again. In the good ol' days, I used to just have onclick="this.disabled=true;this.form.submit();" attribute on the button. When I tried the same in .NET - it doesn't work.
I have validation controls on the form and if user clicked submit while some fields are invalid, the validation controls display messages in red next to each invalid field (common technique). If I added "this.disabled=true" to the onclick event in .NET, then first of all, the form never gets submitted - button stays disabled. If I try something like onclick="this.value='Please wait...'" - also doesn't work, because this changes the button text regardless whether form was valid or not. If it had invalid fields, then validation controls display their messages but the text of the button remains "Please wait..." - confusing to the user because the form looks like it's being submitted, while in fact it's not.
I just can't find a solution to this simple problem! Is there anything on the client side to detect whether form is valid (similar to the server side Page.IsValid) - so you could do something like: onclick="if (this.form.isvalid){this.disabled=true;}" or onclick="if (this.form.isvalid) {this.value='Please wait';}"
validation
mbanavige
All-Star
130696 Points
14322 Posts
ASPInsiders
Moderator
MVP
Re: Disable button on submit to prevent double submission
Dec 23, 2006 01:43 AM|LINK
i believe you will find your answer here: http://www.davidbreyer.com/category/programming/aspnet/
oc1980
Member
44 Points
15 Posts
Re: Disable button on submit to prevent double submission
Dec 23, 2006 02:37 AM|LINK
dmose
Member
68 Points
77 Posts
Re: Disable button on submit to prevent double submission
Aug 01, 2007 03:11 AM|LINK
This is what I wrote to enable this feature:
/// <summary>///
Generates auto-disable butotn /// </summary>///
<param name="p">Page Instance</param> /// <param name="btn">Button Instance</param>///
<param name="disabledText">Text to display on button when clicked</param> /// <param name="aCol">Optional: Collection of controls on page to disable as well (buttons only for now)</param>///
<param name="customScript">Optional: Custom script to run before disabling the button</param>///
<returns></returns> public static string GetLockButtonJscript(Page p, Button btn, string disabledText, ArrayList aCol, string customScript){
disabledText = disabledText == "" ? "Processing..." : disabledText;disabledText = disabledText.Replace("'", "");
StringBuilder sb = new StringBuilder(); if (btn.CausesValidation && p.Validators.Count>0 && btn!=null){
sb.Append("if (typeof(Page_ClientValidate) == 'function') { ");sb.Append("if (Page_ClientValidate('"+btn.ValidationGroup+"') == false) { return false; }} ");}
if (!String.IsNullOrEmpty(customScript)){
sb.Append(customScript);
}
PostBackOptions opt = new PostBackOptions(btn, "", "", false, true, true, true, true, btn.ValidationGroup);sb.Append(p.ClientScript.GetPostBackEventReference(opt));
sb.Append(";");sb.Append(
"this.disabled='true';this.value='" + disabledText + "';"); foreach (Control c in aCol){
if (c is Button){
sb.Append("" + c.UniqueID + ".disabled='true';");}
}
return sb.ToString();}
And how you use it:
protected void btnGlobalSearchSubmit_Load(object sender, EventArgs e){
btnGlobalSearchSubmit.Attributes.Add("onclick", Utils.GetLockButtonJscript(this.Page, btnGlobalSearchSubmit, "Submit", new ArrayList(), ""));}
A more advanced usage:
string questionText = "Are you sure?";
string jScript = "var x=confirm(\"" + questionText + "\");if(!x)return false;";ArrayList a = new ArrayList();a.Add(btnStartOver); //add whatever ADDITIONAL page controls you want to disable when this button is clicked
btnComplete.Attributes.Add(
"onclick", Utils.GetLockButtonJscript(this.Page, btnComplete, btnComplete.Text, a, jScript));So far it works 100% on IE/FireFox/Safari with or without page validators .... if anyone has any improvements or sees any errors let me know thakns!
dmose
Member
68 Points
77 Posts
Re: Disable button on submit to prevent double submission
Aug 21, 2007 04:11 AM|LINK
anyone know why my script is causing a double postback when used on FireFox in an updatepanel?
is it adding a __doPosback twice or something?
Yabadabadoo
Member
247 Points
83 Posts
Re: Disable button on submit to prevent double submission
Jul 22, 2008 04:24 AM|LINK
gg67
Member
4 Points
2 Posts
Re: Disable button on submit to prevent double submission - double-postback fix
Jul 29, 2009 09:23 AM|LINK
Hello,
thanx for your solution dmose, works great in .Net 1.1.
Btw i just fixed the double-postback (Firefox) by appending "return false;". It's all :p
Here my method based on your solution :
Public Shared Sub SetButtonOnClickClientCode( _ ByVal button As System.Web.UI.WebControls.Button, _ ByVal clientScriptCode As String _ ) If (button Is Nothing) Then Throw New ArgumentException("button cannot be null", "button") End If If (button.Page Is Nothing) Then Throw New ApplicationException("the specified button must belong to a page.") End If Dim code As String = clientScriptCode If (code Is Nothing) Then code = String.Empty code = code.Trim() If (code.Length > 0 AndAlso Not code.EndsWith(";")) Then code &= ";" End If Dim onClick As String = String.Empty If (button.CausesValidation AndAlso button.Page.Validators.Count > 0) Then ' Reflectorized from hidden method : ' System.Web.UI.Util.GetClientValidatedPostback onClick = _ "if (typeof(Page_ClientValidate) != 'function' || Page_ClientValidate()) " End If ' ends with 'return false;' to bypass any code ' appended to our string later onClick &= _ "{" & _ code & _ button.Page.GetPostBackEventReference(button) & ";" & _ "}" & _ "return false;" button.Attributes("onclick") = onClick End Sub ' Then u can use something like : SetButtonOnClickClientCode(myButton, "MyJavascriptFunctionToDisableSubmitElements();")SI.Sharma
Member
686 Points
199 Posts
Re: Disable button on submit to prevent double submission
Jul 29, 2009 11:32 AM|LINK
Try this one..
After complition of your operation..add the following code..
btn.Attributes.Add("onclick", "this.disabled=true;");
This will allow only one click..and then after it will disable the button..
Thanks
Kinjal
gg67
Member
4 Points
2 Posts
Re: Disable button on submit to prevent double submission
Jul 29, 2009 02:36 PM|LINK
Nope, it will brokes the client validation, if there is validators on the page (ASP.NET 1.1).
Use the code above, it works.