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

  • Event Date: April 15, 2014 The ability to effectively set sales goals, assign quotas and territories, bring new people on board and quickly make adjustments to the sales force is often crucial to success--and to the field experience! But for sales operations leaders, managing the administrative processes, systems, data and various departments to get it all right can often be difficult, inefficient and manually intensive. Register for this webinar and learn how you can: Align sales goals, quotas and …

  • Cisco and Intel have harnessed flash memory technology and truly innovative system software to blast through the boundaries of today's I/O-bound server/storage architectures. See how they are bringing real-time responsiveness to data-intensive applications—for unmatched business advantage. Sponsored by Cisco and Intel® Partnering in Innovation

Most Popular Programming Stories

More for Developers

Latest Developer Headlines

RSS Feeds