Donate

Enable ASP.NET 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. Ifyou 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);
            }
        }
    )
};

Comments

Donate

Popular Posts From This Blog

WPF CRUD Application Using DataGrid, MVVM Pattern, Entity Framework, And C#.NET

How To Insert Or Add Emojis In Microsoft Teams Status Message

TypeScript Error Or Bug: The term 'tsc' is not recognized as the name of a cmdlet, function, script file, or operable program.