Javascript to Set Focus to a TextBox Control in Asp.Net C# Vb.Net

Sometimes we need to set focus on TextBox control specially after validation failed. To do that we need to know the Javascript method to set focus to TextBox Control. Here in this tips I will explain how one can set focus to a TextBox Control using Javascript as a client block as well as from code behind.

Objective/Output:
Javascript to set focus to a TextBox Control in Asp.Net CSharp VB.Net

To Do the Example Using the below HTML code Block:

    <asp:Label ID="Label1" runat="server" Text="TextBox 1:"></asp:Label>
    <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox><br />
    <asp:Label ID="Label2" runat="server" Text="TextBox 2:"></asp:Label>
    <asp:TextBox ID="TextBox2" runat="server"></asp:TextBox><br />
    <asp:Button ID="Button1" runat="server" Text="Set Focus to TextBox 1" OnClientClick="return Set_Focus_TextBox_1();" />
    <asp:Button ID="Button2" runat="server" Text="Set Focus to TextBox 2 from Code Behind" onclick="Button2_Click" />

Setting Focus to a TextBox Control from Client Side:

    <script type="text/javascript">
        function Set_Focus_TextBox_1() {
            document.getElementById('<%= TextBox1.ClientID %>').focus();
            return false;
        }
    </script>

Setting Focus to a TextBox Control from Server Side/Code Behind:
C# Code:

    protected void Button2_Click(object sender, EventArgs e)
    {
        ClientScript.RegisterStartupScript(this.GetType(), "Focus", "document.getElementById('" + TextBox2.ClientID + "').focus();", true);
    }

VB.Net Code:

    Protected Sub Button2_Click(sender As Object, e As EventArgs)
        ClientScript.RegisterStartupScript(Me.[GetType](), "Focus", "document.getElementById('" & TextBox2.ClientID & "').focus();", True)
    End Sub

Hope now you can set focus to a Asp.Net TextBox Control using Javascript.

Download Code Example C#        Download Code Example VB.Net

Posted in .Net, Asp.net, C#, Client, Javascript, VB.Net

Leave a Reply

Your email address will not be published. Required fields are marked *

AlphaOmega Captcha Classica  –  Enter Security Code
     
 

*