Set default focus and default button in ASP.NET forms

Sometimes it may require to set default focus to an element on a web page. For example if you have a registration form in your web page, with lot of text boxes to be filled in, it will be easy for the user to start typing instantly when the page had loaded instead of moving the cursor towards the first text box to get focus. Also if there is a "submit" button which an user should click on to fire the underlying click event, it would be more desirable for the user to do that by pressing "ENTER" button instead of moving the cursor on to the button and then click on it.

It is very simple and easy to implement this in ASP.NET forms. Consider you have three text boxes and a 'submit' button in your page. When the page loads you want focus to be on the first text box and pressing "ENTER" on your keyboard should trigger the submit button's click event.

<form id="form1" runat="server">
Name :
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
Age :
<asp:TextBox ID="TextBox2" runat="server"></asp:TextBox>
<asp:TextBox ID="TextBox3" runat="server" Height="23px"></asp:TextBox>
<asp:Button ID="Button1" runat="server" Text="Submit" />

To set focus to the first text box and to set submit button as default button of the page simply edit the form tag and add two attributes - defaultbutton, defaultfocus. See the code below.

<form id="form1" runat="server" defaultbutton="Button1" defaultfocus="TextBox1">

Now when the page loads the cursor will be on the first text box enabling the users to type instantly and pressing enter will submit the page.

I hope this post helped you to understand how to set default focus to elements in your web application. Please leave your comments and queries about this post in the comment sections in order for me to improve my writing skills and to showcase more useful posts. Thanks for reading this!!



Dot Net 5640594804835631714

Post a Comment