Monday, December 21, 2009

Disable button by checking validators and invoke server side event

Scenario: - Check whether any validator is triggered. If triggered then don't postback and don't disable the button. If all validators are valid then disable the button and call the server side event.

Solution:-
To solve this scenario , I found out one simple solution using javascript


<script type="text/javascript" language="javascript">
function fnValidate(obj)
{
for(var i=0; i<Page_Validators.length; i++)
{
ValidatorEnable(Page_Validators[i]);

if (Page_Validators[i].isvalid)
{
obj.disabled=true;
}
else
{
obj.disabled=false;
break;
}
}

if (obj.disabled==true)
{
<%=Page.GetPostBackEventReference(btnSubmit)%> }

}

</script>


Call this javascript function in button's OnClientClick property as follows.


<asp:Button ID="btnSubmit" runat="server" Text="Submit" OnClientClick="fnValidate(this);" CausesValidation="true" OnClick="btnSubmit_Click"/>

1 comment: