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

  • On-demand Event Event Date: March 27, 2014 Teams need to deliver quality software faster and need integrated agile planning, task tracking, source control, auto deploy with continuous builds and a configurable process to adapt to the way you work. Rational Team Concert and DevOps Services (JazzHub) have everything you need to build great software, integrated seamlessly together right out of the box or available immediately in the cloud. And with the Rational Team Concert Client, you can connect your …

  • Live Event Date: May 6, 2014 @ 1:00 p.m. ET / 10:00 a.m. PT While you likely have very good reasons for remaining on WinXP after end of support -- an estimated 20-30% of worldwide devices still are -- the bottom line is your security risk is now significant. In the absence of security patches, attackers will certainly turn their attention to this new opportunity. Join Lumension Vice President Paul Zimski in this one-hour webcast to discuss risk and, more importantly, 5 pragmatic risk mitigation techniques …

Most Popular Programming Stories

More for Developers

Latest Developer Headlines

RSS Feeds