Tuesday, March 8, 2016

Enable a control after validation of prior control succeeded using JavaScript in ASP.NET

Given you have a simple form below with two TextBox controls. The second TextBox is disabled during pageload. If you want to enable the second TextBox control if the validation of the first/prior control succeeded, the solution for this is using client side approach which is to check the visibility property through JavaScript/jQuery.
HTML Code
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
<div id="ContactForm">    
        <asp:Label id="lblEmail" Text="Email Address:" AssociatedControlID="txtEmail" Runat="server" />
        <asp:TextBox id="txtEmail" Runat="server" /> 
        <asp:RegularExpressionValidator id="regEmail"
            ControlToValidate="txtEmail" Text="(Invalid email)" 
             ValidationExpression="\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*"
            Runat="server" />    
        <asp:Label id="lblPhone" Text="Phone Number:" AssociatedControlID="txtPhone" Runat="server" />
        <asp:TextBox id="txtPhone" Runat="server" Enabled="false" />     
        <asp:Button id="btnSubmit" Text="Submit" Runat="server" />    
    </div>

The script below will trigger an onblur event of the first TextBox control. It then checks the visibility of the validator control if it's hidden which means successful validation. If true, the second TextBox control is enabled.
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
$(document).ready(function() {
        $('#' + '<%= txtEmail.ClientID %>').blur(function(evt) {
            checkSingleValidators();
        });

        function checkSingleValidators() {
            var isHidden = $('#' + '<%= regEmail.ClientID %>').css('visibility');
            if (isHidden == "hidden") {
                $('#' + '<%= txtPhone.ClientID %>').prop('disabled', false);
            }
        }
    )
};

0 comments:

Post a Comment