Hot Tip
LANGUAGES: C# | JavaScript
TECHNOLOGIES: Web forms
Set Your Focus
Specify which control you want active when a Web form loads.
By Jeff Prosise
Ever wondered how to set the focus to the control of your choice when a Web form loads? If so, you re not alone this question has generated volumes of traffic in newsgroups and in ASP.NET question-and-answer forums. The answer comes in the form of some elementary client-side script. This page, upon loading, sets the focus to the first of its three TextBox controls:
<html>
<body>
<form runat="server">
<asp:TextBox ID="TextBox1" RunAt="server" /><br>
<asp:TextBox ID="TextBox2" RunAt="server" /><br>
<asp:TextBox ID="TextBox3" RunAt="server" />
</form>
</body>
</html>
<script language="javascript">
document.forms[0].TextBox1.focus ();
</script>
It works in Netscape Navigator and Internet Explorer, too!
Jeff Prosise is author of several books, including Programming Microsoft .NET (Microsoft Press). He also is a co-founder of Wintellect (http://www.wintellect.com), a software consulting and education firm that specializes in .NET.