Tuesday, November 16, 2010

Enabling/Disabling asp validators with jquery/Javascript

Today I am going to discuss a situation in which we need the asp:validators to be enabled or disabled by using jquery/javascript.

-------------------------------------------------------------------------------------------------
Asp.net code
<asp:RadioButtonList ID="RblImage" runat="server">
                  <asp:ListItem Value="1">Keep the current Image</asp:ListItem>
                  <asp:ListItem Value="2">Upload new image</asp:ListItem>
                  </asp:RadioButtonList>

<asp:FileUpload ID="FileUpload1" runat="server" />

<asp:Button ID="btnLogo" runat="server" Text="Update Logo"
                          CssClass="blue_btn_cal" onclick="btnLogo_Click" />

<asp:RequiredFieldValidator ID="reqfile" runat="server" ControlToValidate="FileUpload1"
                  ErrorMessage=" Image required" Display="Dynamic"></asp:RequiredFieldValidator>


 I want the required field validator to be enabled only when I select the second option of the radio button list.
----------------------------------------------------------------------------------------------------
Jquery code

$(document).ready(function() {
//for disabling the validators on page load
         var name1 = $('#<%=RblImage.ClientID %> input[type=radio]:checked').val();
         if (name1 != 2) {
             ValidatorEnable(document.getElementById('<%= reqfile.ClientID %>'), false);
         }
         else {
            
             ValidatorEnable(document.getElementById('<%= reqfile.ClientID %>'), true);
         }
         //code for page load ends here
      
$('#<%=btnLogo.ClientID %>').click(function() {
var name = $('#<%=RblImage.ClientID %> input[type=radio]:checked').val();
             if (name == 2) {
        ValidatorEnable(document.getElementById('<%= reqfile.ClientID %>'), true);
}           
else {
                 ValidatorEnable(document.getElementById('<%= reqfile.ClientID %>'), false);
             }

         });
       
     });
------------------------------------------------------------------------------------------------------------
 Here we have checked the value of the radiobuttonlist on button click and then enabled or disabled the validator. On page load we have to check the selected value of the radiobuttonlist and then enable/disable the
valiator because when we click on the button the page will postback and then the validator will be set its initial state which is enabled.

No comments:

Post a Comment