ASP.NET link Enter key with buttons?

I came across a little problem with an ASP.NET web application.

I have several buttons on my page that I want to access by pressing the Enter key (depending on the focus of the TextBox ).

It seemed to me that Googled helped me, but no.

Here is what I found:

 tbEmail.Attributes.Add("onkeydown", "if(event.which || event.keyCode){if ((event.which == 13) || (event.keyCode == 13)) {document.getElementById('" + btRegister.UniqueID + "').click();return false;}} else {return true}; "); 

A source

This does not work, it still presses another button that I do not want to press at the moment.

Any suggestions?

+7
source share
4 answers

It looks like you are using web forms.

You can wrap what you do inside the Panel and set the DefaultButton property inside the panel.

 <asp:Panel ID="LoginPanel" runat="server" DefaultButton="btLogin"> <asp:TextBox ID="txtUser" runat="server" /> <asp:TextBox ID="txtPass" runat="server" /> <asp:Button ID="btLogin" runat="server">Login</asp:Button> </asp:Panel> 

When the user entered the data in txtUser and txtPass , and then press the Enter key, they will launch the btLogin button.

+21
source

Do not try to use JavaScript - place your form inside <asp:Panel> and set the identifier of your button for the DefaultButton property.

+4
source

Using jQuery for this is a lot easier. Bind to keypress event.

+3
source

You can use a keypress event for each text field that will do different things .. like this:

 private void a_keyPress(object sender, KeyPressEventArgs e) { RadTextBox myBox = (RadTextBox)sender; if (e.KeyChar == (char)Keys.Return) { if (myBox.ID == "textbox1") // then do stuff... } else if //do stuff... } 
0
source

All Articles