blog

Home / DeveloperSection / Blogs / Focusing a Textbox using Jquery

Focusing a Textbox using Jquery

Sumit Kesarwani7780 15-Mar-2014

In this blog, I’m explaining how to set focus on textbox on page load using jquery.

Suppose you have login form in your project and you want to set the focus on the username textbox when your login form page loads, this can be achieved by following the below simple steps:

Step 1:

Create a n empty asp.net application and add a webform to it.

Step 2:

Now add two textbox one for username and one for password like this:


Focusing a Textbox using Jquery

Now you want set the focus on the username textbox so that the user can directly write in it. For this you have to download the jquery-1.11.0.min.js file and add it your project.

Step 3:

Now once you have add the jquery-1.11.0.min.js file to your project, you have access to jquery methods and properties and you will be able to write jquery code.

 Add <scriptsrc="jquery-1.11.0.min.js"></script>in the head section of the webfrom by drag and drop from the solution explorer.

Step 4:

Add the below code in the head section of the form :-

<scripttype="text/javascript">
        $(document).ready(function () { //ready method calls before the page loads
            $('#username').focus(); //username is the id of the textbox and focus method set the focus on the textbox.
        });
    </script>

Output

Focusing a Textbox using Jquery

Now you can see the username textbox has focus as soon as the page loads.

Full Code

<%@PageLanguage="C#"AutoEventWireup="true"CodeBehind="Focus.aspx.cs"Inherits="JQueryApp2.WebForm1"%>
<!DOCTYPEhtml>
<htmlxmlns="http://www.w3.org/1999/xhtml">
<headrunat="server">
    <title></title>
    <scriptsrc="jquery-1.11.0.min.js"></script>
    <scripttype="text/javascript">
        $(document).ready(function () {
            $('#username').focus();
        });
    </script>
</head>
<body>
    <formid="form1"runat="server">
        <div>
            Username :
            <inputtype="text"id="username"/><br/>
            Password :
            <inputtype="password"id="password"/>
        </div>
    </form>
</body>
</html>


Updated 18-Sep-2014

Leave Comment

Comments

Liked By