How to let user hit ENTER key after typing username then password
Posted on 2006-11-01
I am all wrapped up in using some new facilities of ASP.NET 2.0 and I feel very confused about how to accomplish this.
I have the basic code working now but I want to have the page submitted automatically when the user has finished
typing the password and simply hits the ENTER key. Should be simple I think but I have a lot pieces here
(code snippets follow):
First, I have a content page (referencing a master page) which includes multiple user controls. One usercontrol has a textbox for entering a zipcode and a button which displays a report when the button is clicked. The other usercontrol has textboxes for entering username and password and a button which handles login processing when clicked. Both usercontrols face the same challenge with the ENTER key; for simplicity, the snippets below relate to the latter user control only:
<%@ Page Language="VB" MasterPageFile="~/Home.master" AutoEventWireup="false" CodeFile="Default.aspx.vb" Inherits="_Default"%>
<%@ Register Src="UILayer/UserControls/LoginMechanism.ascx" TagName="LoginMechanism" TagPrefix="uc1" %>
<asp:Content ID="Content1" ContentPlaceHolderID="ContentPlaceHolder1" Runat="Server">
...then further down in the content page
<uc1:LoginMechanism id="LoginMechanism1" runat="server">
Secondly, inside the usercontrol, here are the webcontrols of interest:
<asp:TextBox ID="Password" runat="server" TextMode="Password"></asp:TextBox>
<asp:RequiredFieldValidator ID="PasswordRequired" runat="server" ControlToValidate="Password"
ErrorMessage="Password is required." ToolTip="Password is required."
<asp:Button ID="LoginButton" runat="server"
Text="Log In" ValidationGroup="ctl00$ctl05$Login1" />
In the code-behind of the usercontrol, I have this code working to place the focus on the button when the page loads:
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Dim sControlName As String = "ctl00_ContentPlaceHolder1_LoginMechanism1_LoginView1_Login1_LoginButton"
Page.ClientScript.RegisterStartupScript(Me.GetType(), "Key1", "<script>document.getElementById('" & _
sControlName & "').focus();</script>")
But of course as soon as I (the user) move to the textboxes for username and password the focus is changed.
I think what I really need is a way to detect that after typing the password the ENTER key is pressed. Or to
rephrase this, how to I "connect" an ASP:Textbox to a particular ASP:Button such that finishing with the
data entry into the button by hitting ENTER causes the desired ASP:Button to automatically clicked?