Home > DeveloperSection > Blogs > Focusing a Textbox using Jquery

Focusing a Textbox using Jquery


JQuery JQuery 
Ratings:
0 Comment(s)
 3407  View(s)
Rate this:

Focusing a Textbox using Jquery

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:


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 <script src="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 :-

<script type="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

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

Full Code

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Focus.aspx.cs" Inherits="JQueryApp2.WebForm1" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">

<head runat="server">

    <title></title>

    <script src="jquery-1.11.0.min.js"></script>

    <script type="text/javascript">

        $(document).ready(function () {

            $('#username').focus();

        });

    </script>

</head>

<body>

    <form id="form1" runat="server">

        <div>

            Username :

            <input type="text" id="username" /><br />

            Password :

            <input type="password" id="password" />

        </div>

    </form>

</body>

</html>


Don't want to miss updates? Please click the below button!

Follow MindStick