ASP.NET Tip: Place Cursor in the First Input Box Automatically | CodeGuru

ASP.NET Tip: Place Cursor in the First Input Box Automatically

Some web sites implement a handy JavaScript function by putting the cursor into the first input text box on a form. This saves the user the step of clicking into the box, speeding up data entry just a bit. Instead of hard-coding JavaScript on every page, I’ve created a handy function that does this for […]

Written By
CodeGuru Staff
CodeGuru Staff
Feb 2, 2007
3 minute read
CodeGuru content and product recommendations are editorially independent. We may make money when you click on links to our partners. Learn More

Some web sites implement a handy JavaScript function by putting the cursor into the first input text box on a form. This saves the user the step of clicking into the box, speeding up data entry just a bit. Instead of hard-coding JavaScript on every page, I’ve created a handy function that does this for you, based on the controls visible on the page. This solution uses the new ASP.NET 2.0 ClientScript manager object in place of the RegisterClientScriptBlock methods that have been deprecated on the Page class.

The following C# code recursively searches the controls on the page to find the first text box and then generates the appropriate JavaScript:

protected void Page_Load(object sender, EventArgs e)
{
   FindFirstTextBox(this);
}

private bool FindFirstTextBox(Control ctl)
{
   bool foundControl = false;
   foreach (Control child in ctl.Controls)
   {
      if (child is TextBox)
      {
         System.Text.StringBuilder script =
            new System.Text.StringBuilder();
         script.AppendFormat("function findFirstControl()n{1}
            n document.getElementById("{0}").focus();n{2}n",
            child.ID, "{", "}");
         ClientScript.RegisterClientScriptBlock(this.GetType(),
         "findFirstControl", script.ToString(), true);
         foundControl = true;
         break;
      }
      if (FindFirstTextBox(child))
      {
         foundControl = true;
         break;
      }
   }
   return foundControl;
}

Because the controls are added in order to the Controls collection, the first one found is the one that should be at the topmost and leftmost position. The code runs recursively because you may have container controls (such as panels, forms, or tables) that contain the actual text boxes. Once it finds the first control, it generates a block of JavaScript code that will, when called, find the first text box control based on the name it located. The last step is to call the function at the bottom of the page. If you try to call the function before the form HTML, the function won’t be able to find the text box in question.

This example calls the ClientScript.RegisterClientScriptBlock method, which is new in ASP.NET 2.0. The first argument is the type of script, and sending in the type of the page (retrieved using GetType()) works fine here. The second argument is the name being assigned to this script block. This is used in conjunction with the new IsClientScriptBlockRegistered method on the ClientScript object, which lets you verify that you haven’t already added a particular script block to the page. The third argument is the actual JavaScript code, and the fourth indicates whether the opening and closing SCRIPT tags should be added to the output. An additional overload on this method leaves out the fourth argument and always includes the SCRIPT tags. This registration adds the script to the output HTML but doesn’t execute it right away because the JavaScript being added is actually a function. I call it at the bottom of the HTML form.

Any HTML form will work for this example—the key is to add the call to the findFirstControl function at the bottom of the page, as shown here:

   ... form content above ...
            <tr>
               <td align="right" width="200">
                  Address, Line 2:</td>
               <td width="400">
                  <asp:TextBox ID="txtAddressLine2" runat="server"
                               MaxLength="80"
                               Style="width: 300px" /></td>
            </tr>
            <tr>
               <td align="right" width="200">
                  City:</td>
               <td width="400">
                  <asp:TextBox ID="txtCity" runat="server"
                               MaxLength="40"
                               Style="width: 150px" /></td>
            </tr>
         </table>
      </div>
   </form>
   <script type="text/javascript">
      findFirstControl();
   </script>
</body>
</html>

In my testing, Internet Explorer 7.0 did not always select the first field after the initial load. If your cursor is in the second field and you reload the page, the cursor stays in the second field. However, testing in Firefox 2.0 showed that the JavaScript puts the cursor into the first field on the page every time.

About the Author

Eric Smith is the owner of Northstar Computer Systems, a Web-hosting company based in Indianapolis, Indiana. He is also a MCT and MCSD who has been developing with .NET since 2001. In addition, he has written or contributed to 12 books covering .NET, ASP, and Visual Basic. Send him your questions and feedback via e-mail at questions@techniquescentral.com.

CodeGuru Logo

CodeGuru covers topics related to Microsoft-related software development, mobile development, database management, and web application programming. In addition to tutorials and how-tos that teach programmers how to code in Microsoft-related languages and frameworks like C# and .Net, we also publish articles on software development tools, the latest in developer news, and advice for project managers. Cloud services such as Microsoft Azure and database options including SQL Server and MSSQL are also frequently covered.

Property of TechnologyAdvice. © 2026 TechnologyAdvice. All Rights Reserved

Advertiser Disclosure: Some of the products that appear on this site are from companies from which TechnologyAdvice receives compensation. This compensation may impact how and where products appear on this site including, for example, the order in which they appear. TechnologyAdvice does not include all companies or all types of products available in the marketplace.