Link to home
Start Free TrialLog in
Avatar of skateboard
skateboard

asked on

Disable Button on a form before code runs

I have a button that onclick runs a lot of code.  It takes 2-3 seconds to run through all of the code.  The Problem that I have is the user can click the button more than once.  So I get duplicate records and all the problems that go with that.  The system also sends multiple e-mails and various other problems.  I need to disable the button after it has been clicked so that it can not be clicked again whlile the code runs.  It is an Imagebutton and I am writing in asp.net VB.  A simple btnsend.enabled=false will not work because it does not disable the button until the page has run through all of the code.  Any ideas?

Thanks for the help
Avatar of Ghecco
Ghecco

add a function which will first disalble your button and then run all the code ...
Avatar of skateboard

ASKER

Well yes, but I have to postback the page first.  To get the button to go disabled that seems like the slow way to do it.  Unless you know of a better way.  I am looking for a way to make the button become disabled on the click and not have to wait for the postback that comes when all of the code has run.
The web page is generated when the render method is run. All your event handlers execute before it, so a new refreshed page is only returned when the whole page is done and dealt with. You cannot change this behavior through server-side scripting.

You could use client-side Javascript to disable the button immediately after the submission, but that is a path with some problems: what if the submission gets aborted? The user has no way to re-send the information even in that case. And yeah, if the user doesn't have JS enabled, he will be able to double submit anyway.

Another approach is to return a quick blank page with text like "Processing, please wait" and then redirect to another page which actually does the job, but this can be problematic especially with large form submissions.

For what it's worth: Personally I don't think what you're doing is the right approach to the problem; a better one would be to do some work to prevent double submissions from being processed. That way you'll be better off even with the strange browser combinations you may encounter.
Avatar of Dannin

if condition then

e.cancel = true

else
insert

End if
Let me give more detail and see if that helps.

Sub Page_Load(Sender as Object, e As EventArgs)
      If btnSubmit.Visible=False Then
            Process_Click
      Else
            Exit Sub
      End If
End Sub


Sub Button_Click(sender As Object, e As System.Web.UI.ImageClickEventArgs)
      btnSubmit.Visible=False                              'Disable the button Click                              lblsaving.text="<font color=#FF0000><B>Processing, please wait...</B></font>"
End Sub
      
Sub Process_Click runs code that I know works fine.  I have 2 problems.  First the button does disable and the label says what it should but the sub Process_Click does not run.  The other problem I have is when I post back to make the button invisible and display the label it clears the text out of the password field.  So My password field has no value.

That didnt post well.  The lblsaving.text is on a new line so it is not coment tagged
Button_Click gets called _after_ Page_Load is called, so btnSubmit.Visible is True when Page_Load is getting called. After that, Button_Click sets it to false, but this doesn't cause Process_Click to be started.
Button click is only called when the button is clicked.  So that code runs only when the button is clicked.
Yes, of course. But you said your problem is that Process_Click doesn't get called, and I told you why. When you click the button, "Page_Load" is run first. That If condition is false, so "Exit Sub" is run. Therefore, Process_Click is not. After that, Button_Click is run, but the changes is makes are no longer relevant to Page_Load, so there's no place to call Process_Click left.
hmmm... Are you sure?  I read that as If the button is not visible then run the Process Click sub.  Othewise if the button is visible exit the Page_Load sub.  How would you write this?
Yes, you read Page_Load exactly correctly. Your problem is that your button is still visible when Page_Load is run, so it just exits the sub without running the processing code.

These things are a bit hard to do well. You should read my first comment on this question and consider if you can focus on writing code to prevent a disaster _if_ a duplicate submission happens. If that's not possible, then an intermediate page approach like you've been trying might be feasible. To know what's truly best, one would have to what's on the form you're submitting.
Yeah I should have said that I agree with that.  However in this case I dont have control over A LOT of things.  The Database I have no control over as well as the way that data is passed through the system.

The page posts back when the button is clicked.  So I assume that it runs the page_Load sub again.  Is that not correct?  I am Posting a password, a Fname and a Lname to the database.  That is all the data that is being collected on the Form.
Yes. The whole cycle goes like this:

1) The user types your url into the browser.
2) The Page_Load gets called.
3) The controls are rendered as HTML and sent to the user.

Now, the user spends time pondering whether or not to click on that button. Let's assume he does. The page is loaded once more.

4) Page_Load gets called. (notice that nobody has yet set the button's visible property to false)
5) Button_Click gets called. (now the button is set invisible and the label text gets modified)
6) The page content is rendered to the browser.


At this point, I think the easiest way would be to include a hidden Html field in the original form and make its value something unique (a random identifier, a datetime, pick whatever you want). Now, when you start processing the form submit, you check that a session variable doesn't already contain that identifier. If it does, you cancel out - this is obviously a duplicate submission. If it doesn't, save the hidden field's value to the session variable and start the DB update.

That way you don't have to worry about duplicates. You won't get that cool intermediate "Processing" notice though, but the solution is fairly safe and easy to implement.
>> I am looking for a way to make the button become disabled on the click
>> and not have to wait for the postback that comes when all of the code has run.
You can still using JavaScript to disable the submit button and Page.RegisterOnSubmitStatement method to access the client functions.

Assuming the submit button is "button1"

[VB.NET]
Private Sub DisableOnSubmitScript()

  Dim oBuffer As System.Text.StringBuilder = new System.Text.StringBuilder()

  oBuffer.Append("<script language=""javascript"">").Append(Environment.NewLine)
  oBuffer.Append("<!--").Append(Environment.NewLine)
  oBuffer.Append(Environment.NewLine)
  oBuffer.Append("function DisableOnSubmit() {").Append(Environment.NewLine)
  oBuffer.Append("document.all['").Append(this.Button1.UniqueID).Append("'].disabled = true;").Append(Environment.NewLine)
  oBuffer.Append(Environment.NewLine)
  oBuffer.Append("alert('Submit button is disabled');").Append(Environment.NewLine)
  oBuffer.Append("    return true;").Append(Environment.NewLine)
  oBuffer.Append("}").Append(Environment.NewLine)
  oBuffer.Append(Environment.NewLine)
  oBuffer.Append("//-->").Append(Environment.NewLine)
  oBuffer.Append("</script>").Append(Environment.NewLine)

  this.RegisterClientScriptBlock("_DisableOnSubmitScript", oBuffer.ToString())
  this.RegisterOnSubmitStatement("_DisableOnSubmit", "DisableOnSubmit();")

End Sub

Put the method in your webform class and call either from Page_Load or Page_PreRender event

Sub Page_Load(Sender as Object, e As EventArgs)
    If Page.IsClientScriptBlockRegistered("_DisableOnSubmitScript") = False Then
          DisableOnSubmitScript()
    End If
End Sub

Or

Private Sub Page_PreRender(sender As Object, e As System.EventArgs)
  DisableOnSubmitScript()
End Sub

The submit button is disabled on click and cannot be re-submit before postback. Then back to normal state after page is fully rendered.

hope this helps
I know very little about javascript.  I get the following error.

Compiler Error Message: BC30451: Name 'this' is not declared.
it was talking about this line.

oBuffer.Append("document.all['").Append(this.button1.UniqueID).Append("'].disabled = true;").Append(Environment.NewLine)
oops sorry..., I just converted from C# to VB.NET by directly typing to this textbox. Replace with Me instead.

oBuffer.Append("document.all['").Append(Me.button1.UniqueID).Append("'].disabled = true;").Append(Environment.NewLine)

When you click the button you'll see popup message saying 'Submit button is disabled' and the the button is disabled. After that you can remove the line:

oBuffer.Append("alert('Submit button is disabled');").Append(Environment.NewLine)
Now I get this error:

Compiler Error Message: BC30648: String constants must end with a double quote

oBuffer.Append("</script>").Append(Environment.NewLine)


Thanks for the help
I've fixed it, try this again

Private Sub DisableOnSubmitScript()

      Dim oBuffer As System.Text.StringBuilder = New System.Text.StringBuilder()

      oBuffer.Append("<script language=""javascript"">").Append(Environment.NewLine)
      oBuffer.Append("<!--").Append(Environment.NewLine)
      oBuffer.Append(Environment.NewLine)
      oBuffer.Append("function DisableOnSubmit() {").Append(Environment.NewLine)
      oBuffer.Append("document.all['").Append(Me.Button1.UniqueID).Append("'].disabled = true;").Append(Environment.NewLine)
      oBuffer.Append(Environment.NewLine)
      oBuffer.Append("alert('Submit button is disabled');").Append(Environment.NewLine)
      oBuffer.Append("    return true;").Append(Environment.NewLine)
      oBuffer.Append("}").Append(Environment.NewLine)
      oBuffer.Append(Environment.NewLine)
      oBuffer.Append("//-->").Append(Environment.NewLine)
      oBuffer.Append("</script>").Append(Environment.NewLine)

      Me.RegisterClientScriptBlock("_DisableOnSubmitScript", oBuffer.ToString())
      Me.RegisterOnSubmitStatement("_DisableOnSubmit", "DisableOnSubmit();")

End Sub
I still get this,

Compilation Error
Description: An error occurred during the compilation of a resource required to service this request. Please review the following specific error details and modify your source code appropriately.

Compiler Error Message: BC30648: String constants must end with a double quote.

It is talking about this line.

oBuffer.Append("</script>").Append(Environment.NewLine)

mm.. strange, I've tested and worked perfectly in my VS.NET. Try to replace each single quote in the method with two double qoutes.
Do you have IIS to test it on?  I get the same error on 3 different servers.  I also replaced the single' to "" and get the same error.
You got compile error or runtime error? I've compiled and nothing wrong in my VS.NET, then I've tested by running the browser, it worked as expected.

Try to remove the whole method and re-compile. Let's see if it still gives you the same error.
Here is my code as I am testing it.

<%@ Page Language="vb" Explicit="true" Debug="true"%>
<script runat="server">

Sub Page_Load(Sender as Object, e As EventArgs)
   If Page.IsClientScriptBlockRegistered("_DisableOnSubmitScript") = False Then
          DisableOnSubmitScript()
   End If
End Sub

Private Sub DisableOnSubmitScript()

    Dim oBuffer As System.Text.StringBuilder = New System.Text.StringBuilder()

    oBuffer.Append("<script language=""javascript"">").Append(Environment.NewLine)
    oBuffer.Append("<!--").Append(Environment.NewLine)
    oBuffer.Append(Environment.NewLine)
    oBuffer.Append("function DisableOnSubmit() {").Append(Environment.NewLine)
    oBuffer.Append("document.all['").Append(Me.Button1.UniqueID).Append("'].disabled = true;").Append(Environment.NewLine)
    oBuffer.Append(Environment.NewLine)
    oBuffer.Append("alert('Submit button is disabled');").Append(Environment.NewLine)
    oBuffer.Append("    return true;").Append(Environment.NewLine)
    oBuffer.Append("}").Append(Environment.NewLine)
    oBuffer.Append(Environment.NewLine)
    oBuffer.Append("//-->").Append(Environment.NewLine)
    oBuffer.Append("</script>")".Append(Environment.NewLine)

    Me.RegisterClientScriptBlock("_DisableOnSubmitScript", oBuffer.ToString())
    Me.RegisterOnSubmitStatement("_DisableOnSubmit", "DisableOnSubmit();")

End Sub

</script>
<html>

<head>

<title>New Page 1</title>
</head>

<body>
<form runat=server>
<asp:Button ID=button1 Runat=server/>
<asp:Label ID=lbl1 Runat=server/>
</form>

</body>

</html>
Make that this is the code that I am using.  I messed with the one before trying to get it to work

<%@ Page Language="vb" Explicit="true" Debug="true"%>
<script runat="server">

Sub Page_Load(Sender as Object, e As EventArgs)
   If Page.IsClientScriptBlockRegistered("_DisableOnSubmitScript") = False Then
          DisableOnSubmitScript()
   End If
End Sub

Private Sub DisableOnSubmitScript()

    Dim oBuffer As System.Text.StringBuilder = New System.Text.StringBuilder()

    oBuffer.Append("<script language=""javascript"">").Append(Environment.NewLine)
    oBuffer.Append("<!--").Append(Environment.NewLine)
    oBuffer.Append(Environment.NewLine)
    oBuffer.Append("function DisableOnSubmit() {").Append(Environment.NewLine)
    oBuffer.Append("document.all['").Append(Me.Button1.UniqueID).Append("'].disabled = true;").Append(Environment.NewLine)
    oBuffer.Append(Environment.NewLine)
    oBuffer.Append("alert('Submit button is disabled');").Append(Environment.NewLine)
    oBuffer.Append("    return true;").Append(Environment.NewLine)
    oBuffer.Append("}").Append(Environment.NewLine)
    oBuffer.Append(Environment.NewLine)
    oBuffer.Append("//-->").Append(Environment.NewLine)
    oBuffer.Append("</script>").Append(Environment.NewLine)

    Me.RegisterClientScriptBlock("_DisableOnSubmitScript", oBuffer.ToString())
    Me.RegisterOnSubmitStatement("_DisableOnSubmit", "DisableOnSubmit();")

End Sub

</script>
<html>

<head>

<title>New Page 1</title>
</head>

<body>
<form runat=server>
<asp:Button ID=button1 Runat=server/>
<asp:Label ID=lbl1 Runat=server/>
</form>

</body>

</html>

This the problem:
oBuffer.Append("</script>")".Append(Environment.NewLine)

Replace with  this:
oBuffer.Append("</script>").Append(Environment.NewLine)
hehehehe, yeah I posted the wrong code before.  You were probably writing that as I posted the code I was really using.

I guess you typed it wrongly, if you see my previous comment I typed it correctly. Okay, hope can work now.
Still the same thing.  Can you run my code and get it to work.  Also is there a namespace I need to import that I am not?

Alright, follow these instructions:
1. Remove your webform (by default VS.NET will delete it permanently)
2. Open your notepad, save it as WebForm1.aspx then copy and paste the code below

=========================================================
<%@ Page Language="vb" AutoEventWireup="false" Codebehind="WebForm1.aspx.vb" Inherits="WebApplication1.WebForm1"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML>
      <HEAD>
            <title>WebForm1</title>
            <meta name="GENERATOR" content="Microsoft Visual Studio.NET 7.0">
            <meta name="CODE_LANGUAGE" content="Visual Basic 7.0">
            <meta name="vs_defaultClientScript" content="JavaScript">
            <meta name="vs_targetSchema" content="http://schemas.microsoft.com/intellisense/ie5">
      </HEAD>
      <body MS_POSITIONING="GridLayout">
            <form id="Form1" method="post" runat="server">
                  <asp:Button id="Button1" style="Z-INDEX: 101; LEFT: 8px; POSITION: absolute; TOP: 8px" runat="server" Text="Button"></asp:Button>
            </form>
      </body>
</HTML>
=========================================================

3. Open another new notepad, save it as WebForm1.aspx.vb, copy and paste the code below

=========================================================
Public Class WebForm1
    Inherits System.Web.UI.Page
    Protected WithEvents Button1 As System.Web.UI.WebControls.Button

#Region " Web Form Designer Generated Code "

    'This call is required by the Web Form Designer.
    <System.Diagnostics.DebuggerStepThrough()> Private Sub InitializeComponent()

    End Sub

    Private Sub Page_Init(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Init
        'CODEGEN: This method call is required by the Web Form Designer
        'Do not modify it using the code editor.
        InitializeComponent()
    End Sub

#End Region

    Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        'Put user code to initialize the page here
        If Page.IsClientScriptBlockRegistered("_DisableOnSubmitScript") = False Then
            DisableOnSubmitScript()
        End If
    End Sub

    Private Sub DisableOnSubmitScript()

        Dim oBuffer As System.Text.StringBuilder = New System.Text.StringBuilder()

        oBuffer.Append("<script language=""javascript"">").Append(Environment.NewLine)
        oBuffer.Append("<!--").Append(Environment.NewLine)
        oBuffer.Append(Environment.NewLine)
        oBuffer.Append("function DisableOnSubmit() {").Append(Environment.NewLine)
        oBuffer.Append("document.all['").Append(Me.Button1.UniqueID).Append("'].disabled = true;").Append(Environment.NewLine)
        oBuffer.Append(Environment.NewLine)
        oBuffer.Append("alert('Submit button is disabled');").Append(Environment.NewLine)
        oBuffer.Append("    return true;").Append(Environment.NewLine)
        oBuffer.Append("}").Append(Environment.NewLine)
        oBuffer.Append(Environment.NewLine)
        oBuffer.Append("//-->").Append(Environment.NewLine)
        oBuffer.Append("</script>").Append(Environment.NewLine)

        Me.RegisterClientScriptBlock("_DisableOnSubmitScript", oBuffer.ToString())
        Me.RegisterOnSubmitStatement("_DisableOnSubmit", "DisableOnSubmit();")

    End Sub

End Class
=========================================================
4. Copy the two files to your project folder
5. From the menu Project->Add existing item, a dialog box open
6. Make sure the File of type is selecting the WebFiles (*.aspx, *.ascx, etc)
7. Select the WebForm1.aspx
8. Press F5
Sometimes I really dont like MS.

Your code runs fine in VS.net and under IIS if I run it in the same folder with all of those other files.  The problem is I need this to be in one maybe 2 files.  I know I need the 2 files I created but it wont run with just those 2 files.  What else am I going to have to have in order to make this run?  
Thanks again for the help.  Ill up the points when I award them
OK I think I have it.  The dll is really all I need to make this work.  Is there a way to make a label print out using the same javascript block to replace
 lblsaving.text="<font color=#FF0000><B>Processing, please wait...</B></font>"  
from my post.  Thanks again

You meant you managed to run the code? sorry I don't really understand with the 2 files, dll and label print out. Can you please clarify in more detail?
I did get the code to run local.  I dont use VS.net most of the time.  That was part of my problem.  I code in notepad.  When I used VS.net it created a dll in the bin folder.  I moved the aspx the aspx.vb and the bin/.dll to another server and the code errors.  It tells me its looking for " Inherits="WebApplication1.WebForm1"

As for the Label, in my 3rd post I was adding text to a label control that said "Processing, please wait..".  That was when I was using asp.net to make the label show.  The problem is that I need a postback for the label to show and the postback does not happen until the code from button1_Click has run.  Which is to late because that code directs the user to another page.  So what I was asking is, Is there a way to put a label on the page using Javascripst at the same time that the button is disabled.  Or can I control a label control that already has the text in to to be visible with the javascript?

skateboard, coding an asp.net application without VS.NET definitely is not a good choice, since it offers many features to ease your programming tasks. And your 2nd Q (so you have 2Qs here :o), nevermind), showing and hiding control using javascript is not difficult at all. But I won't move on till you solve the first problem.

Please create a new project using VS.NET, add control using drag and drop from toolbox to webform, and use copy and paste to insert the method I've given you. Please let me know if you have problem.
I have the code working fine.  Problem is it does not work in netscape.  I dont think its a netscape settings issue, I have tried it on a few different systems.  The code runs fine in IE
yes, that because document.all only exists under IE 4 or later and not in Netscape. Please check this out to make it works in IE or Netscape:
http://developer.irt.org/script/1191.htm
Ok from that I take it that i need this as my javascript.

<script language="javascript">
   <!--

   function DisableOnSubmit() {
    if (document.layers && document.layers[Me.Button1.UniqueID])
        document.layers[Me.Button1.UniqueID].visibility = 'hidden';
    else if (document.all)
        document.all[Me.Button1.UniqueID].style.visibility = 'hidden';
}
//--></script>


Can you show me how to put that label on the page, The same action will trigger the label as triggers the button being inactive.  Can I put that code in the same script or will I need another script?

The script should like the following:

<script language="javascript">
<!--
var ctl_1;      // button control
var ctl_2;      // label control

if (document.all) {
      // IE browser
      ctl_1 = document.all['Button1'];
      ctl_2 = document.all['Label1'];
      document.all['Label1'].style.visibility = 'hidden';
}
else if (document.layers) {
      // Netscape browser
      ctl_1 = document.layers['Button1'];
      ctl_2 = document.layers['Label1'];
}
else if (document.getElementById) {
      // Others
      ctl_1 = document.getElementById('Button1');
      ctl_2 = document.getElementById('Label1');
}

ctl_2.style.visibility = 'hidden'

function DisableOnSubmit() {
      if (ctl_1) {
            ctl_1.disabled = true;
      }
      if (ctl_2) {
            ctl_2.style.visibility = 'visible';
      }
      alert('okay!');      // this line should be removed later
      return true;
}
//-->
</script>
[VB.NET]

Private Sub DisableOnSubmitScript()

   Dim sScript As String = "<script language=""javascript"">""
   sScript += ("<!--")
   sScript += Environment.NewLine
   sScript += "var ctl_1;  // button control"
   sScript += "var ctl_2;  // button control")
   sScript += "var name_1 = '" + Me.Button1.UniqueID
   sScript += "var name_2 = '" + Me.Label1.UniqueID
   sScript += Environment.NewLine
   sScript += "if (document.all) {"
   sScript += "   // IE browser"
   sScript += "   ctl_1 = document.all[name_1];"
   sScript += "   ctl_2 = document.all[name_2];"
   sScript += "}"
   sScript += "else if (document.layers) {"
   sScript += "      // Netscape browser"
   sScript += "      ctl_1 = document.layers[name_1];"
   sScript += "      ctl_2 = document.layers[name_2];"
   sScript += "}"
   sScript += "else if (document.getElementById) {"
   sScript += "      // Others"
   sScript += "      ctl_1 = document.getElementById(name_1);"
   sScript += "      ctl_2 = document.getElementById(name_2);"
   sScript += "}"
   sScript += Environment.NewLine
   sScript += "ctl_2.style.visibility = 'hidden'"
   sScript += Environment.NewLine
   sScript += "function DisableOnSubmit() {"
   sScript += "      if (ctl_1) {"
   sScript += "            ctl_1.disabled = true;"
   sScript += "      }"
   sScript += "      if (ctl_2) {"
   sScript += "            ctl_2.style.visibility = 'visible';"
   sScript += "      }"
   sScript += "      alert('okay!');      // this line should be removed later"
   sScript += "      return true;"
   sScript += "}"
   sScript += Environment.NewLine
   sScript += "//-->"
   sScript += "</script>"
   
   Me.RegisterClientScriptBlock("_DisableOnSubmitScript", sScript)
   Me.RegisterOnSubmitStatement("_DisableOnSubmit", "DisableOnSubmit();")

End Sub

Sorry, change the line:

Me.RegisterClientScriptBlock("_DisableOnSubmitScript", sScript)

To:

Me.RegisterStartupScript("_DisableOnSubmitScript", sScript)

Hi any problem with the code?
Hi I had to change it a bit.  there were a few problems all but 1 is  fixed.  It did not like
Dim sScript As String = "<script language=""javascript"">""
So I changed it to:
 Dim sScript As String = "<script language=javascript>"

and it seems to run fine.  

For some reason it was reading this:

 sScript += "</script>"

As the end of my .net script so I changed to this:

Dim End1 as String = "ript>"
Dim End2 As String = "</sc"

sScript += End2 + End1

Ghetto, but it works.

Because your code produced 3 or 4 lines of code the comment tags were killing off half the code.  

The code currently executes fine on both IE and Netscape, However  in the toolbar on IE it says page finished with errors.  It says that Me is undefined in the line:

Me.Button1.UniqueID

I also Tried

document.form.[Button1.UniqueID]

But I get the error of button1 is either null or not an object.

Here is my code as I have it right now.

Private Sub DisableOnSubmitScript()

      Dim End1 as String = "ript>"
        Dim End2 As String = "</sc"
        Dim sScript As String = "<script language=javascript>"
        
  sScript += ("<!--")
  sScript += Environment.NewLine
  sScript += "var ctl_1;" & Environment.NewLine
  sScript += "var ctl_2;" & Environment.NewLine
  sScript += "var name_1 = " + "document.form.[Button1.UniqueID]"  & Environment.NewLine
  sScript += "var name_2 = " + "document.form.[Label1.UniqueID]"  & Environment.NewLine
  sScript += Environment.NewLine
  sScript += "if (document.all) {" & Environment.NewLine
  sScript += "   ctl_1 = document.all[name_1];" & Environment.NewLine
  sScript += "   ctl_2 = document.all[name_2];" & Environment.NewLine
  sScript += "}" & Environment.NewLine
  sScript += "else if (document.layers) {" & Environment.NewLine
  sScript += "     ctl_1 = document.layers[name_1];" & Environment.NewLine
  sScript += "     ctl_2 = document.layers[name_2];" & Environment.NewLine
  sScript += "}" & Environment.NewLine
  sScript += "else if (document.getElementById) {" & Environment.NewLine
  sScript += "     ctl_1 = document.getElementById(name_1);" & Environment.NewLine
  sScript += "     ctl_2 = document.getElementById(name_2);" & Environment.NewLine
  sScript += "}" & Environment.NewLine
  sScript += Environment.NewLine
  sScript += "ctl_2.style.visibility = 'hidden'" & Environment.NewLine
  sScript += Environment.NewLine
  sScript += "function DisableOnSubmit() {" & Environment.NewLine
  sScript += "     if (ctl_1) {" & Environment.NewLine
  sScript += "          ctl_1.disabled = true;" & Environment.NewLine
  sScript += "     }" & Environment.NewLine
  sScript += "     if (ctl_2) {" & Environment.NewLine
  sScript += "          ctl_2.style.visibility = 'visible';" & Environment.NewLine
  sScript += "     }" & Environment.NewLine
  sScript += "     alert('okay!');" & Environment.NewLine
  sScript += "     return true;" & Environment.NewLine
  sScript += "}" & Environment.NewLine
  sScript += Environment.NewLine
  sScript += "//-->" & Environment.NewLine
  sScript += Environment.NewLine
  sScript += End2 + End1
 
  Me.RegisterStartupScript("_DisableOnSubmitScript", sScript)
  Me.RegisterOnSubmitStatement("_DisableOnSubmit", "DisableOnSubmit();")

End Sub

ASKER CERTIFIED SOLUTION
Avatar of mondayblueboy
mondayblueboy

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial

Run the project. Right click the browser and select "View Source' you'll see the following javascript code:

<SCRIPT language=javascript>
<!--

var ctl_1;  // button control
var ctl_2;  // button control
var name_1 = 'Button1'
var name_2 = 'Label1'

if (document.all) {
   // IE browser
   ctl_1 = document.all[name_1];
   ctl_2 = document.all[name_2];
}
else if (document.layers) {
     // Netscape browser
     ctl_1 = document.layers[name_1];
     ctl_2 = document.layers[name_2];
}
else if (document.getElementById) {
     // Others
     ctl_1 = document.getElementById(name_1);
     ctl_2 = document.getElementById(name_2);
}

ctl_2.style.visibility = 'hidden'

function DisableOnSubmit() {
     if (ctl_1) {
          ctl_1.disabled = true;
     }
     if (ctl_2) {
          ctl_2.style.visibility = 'visible';
     }
     alert('okay!');     // this line should be removed later
     return true;
}

//-->
</SCRIPT>
Using this solution would mean that the builtin ASP.NET validations would not work ...!!!
Yes thats the problem that I ran into and have not solved.  Also for some reason its not calling both the javascript and the sub button_Click.

Do you have another idea Ghecco?
This should solved the problem:

Button.Attributes.Add does not work after I added Validation control on the page
https://www.experts-exchange.com/questions/20768006/button-Attributes-Add-does-not-work-after-I-added-Validation-control-on-the-page.html