Disable button on post back – working with validators

In the past I’ve written a post on how to disable a button on post back:

Disable button on past back

   1: <script language="javascript" type="text/javascript">
   2: <!--
   3:    function disableAndPost()
   4:    {
   5:       <%= ClientScript.GetPostBackEventReference(btnDoSomething, "") %>;
   6:       document.getElementById('<%=btnDoSomething.ClientID %>').disabled="disabled";
   7:    }
   8: -->
   9: </script>


This works really nicely, until you try use this with ASP.NET Validators.

Fortunately, there is a simple work around for this.
We need to check is the javascription function Page_ClientValidate() is true or false.

This can be achieved easily by modifying the above code as follows:

   1: <script language="javascript" type="text/javascript">
   2: <!--
   3:    function disableAndPost()
   4:    {
   5:       if (typeof(Page_ClientValidate) == 'function')
   6:         if (Page_ClientValidate() == false)
   7:            return false; 
   8:       <%= ClientScript.GetPostBackEventReference(btnDoSomething, "") %>;
   9:       document.getElementById('<%=btnDoSomething.ClientID %>').disabled="disabled";
  10:    }
  11: -->
  12: </script>

 

This will exit out of the function if the form is not yet validated.
Simple as that!

posted @ Monday, January 26, 2009 1:05 PM

Print
«February»
SunMonTueWedThuFriSat
28293031123
45678910
11121314151617
18192021222324
25262728123
45678910