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 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.



Comments

  • There are no comments yet. Be the first to comment!

Leave a Comment
  • Your email address will not be published. All fields are required.

Top White Papers and Webcasts

  • Today's competitive marketplace requires the organization to frequently release and deploy applications at the pace of user demands, with reduced cost, risk, and increased quality. This book defines the basics of application release and deployment, and provides best practices for implementation with resources for a deeper dive. Inside you will find: The business and technical drivers behind automated application release and deployment. Evaluation guides for application release and deployment solutions. …

  • Live Event Date: April 22, 2014 @ 1:00 p.m. ET / 10:00 a.m. PT Database professionals — whether developers or DBAs — can often save valuable time by learning to get the most from their new or existing productivity tools. Whether you're responsible for managing database projects, performing database health checks and reporting, analyzing code, or measuring software engineering metrics, it's likely you're not taking advantage of some of the lesser-known features of Toad from Dell. Attend this live …

Most Popular Programming Stories

More for Developers

Latest Developer Headlines

RSS Feeds