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

  • Gain buy-in, choose the right tools, and encourage employees to participate. Whether you need help introducing social media or making your efforts more successful, this is the guide for you. It contains 140 tips in tweet form (140 characters or less) with ideas for promoting social media, deciding which venues to use, and encouraging participation. Plus, the guide contains links to social media statistics, informative websites, and other resources.

  • Cloud computing isn't new, but it's still a hot topic in technology circles. Moving to the cloud has done great things for many businesses. When it comes to handling a basic business necessity, cloud computing has brought many improvements to overall business continuity. Using the cloud for DR makes a lot of sense for many, but it's not exactly the most simple concept. Read this eBook to find answers to all the key questions IT professionals have about cloud-based disaster recovery, and helpful info around the …

Most Popular Programming Stories

More for Developers

RSS Feeds

Thanks for your registration, follow us on our social networks to keep up-to-date