enter key in asp.net firing wrong button
Asked Answered
D

3

19

I have a text box and many buttons. When user is in some text box and presses the "enter" key then specific button click event is raised. I read on the internet that there are some problems with the "enter" key and I tried few solutions but still it always enters that button event (that button is the first button in the page).

I tried creating a button which does nothing and writing this in the page_load:

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

All my page controls are in a form and I tried giving the form "defaultButton" property to that button I created. That didnt work either.

Any idea why this isn't working and what am I doing wrong?

Disrespectable answered 12/8, 2010 at 11:11 Comment(2)
Possible duplicate of how to set a default 'enter' on a certain buttonCoast
The two questions are so similar that I wasn't sure which one to flag. StackOverflow's trend is to pick the clearer anf better formatted question, not the one that was posted first. In this case however, even the phrasing was similar enough, so I went with the more popular question and the one that had more votes. Sorry.Coast
A
39

The standard way in ASP.NET to control which submit button is activated when ENTER is pressed is to wrap the controls and buttons in an asp:Panel with the DefaultButton property set to the correct button.

If I'm reading your question properly, you just want one specific button to be activated when ENTER is pressed, so wrap everything on your page in a single asp:Panel.

<asp:Panel id="pnlDefaultButton" runat="server" DefaultButton="btnOK">
    <!-- All controls here including: -->
    <asp:Button id="btnOK" runat="server" Text="OK" />
</asp:Panel>
Alexisaley answered 12/8, 2010 at 15:15 Comment(3)
What about asp:Content? I use master pages and have no panel nor form on my page.Celebrate
@Celebrate - I'm not certain what you mean. Using master pages doesn't change much, unless the button is in one content section and the other parts of the page somewhere else. In that situation, you could rearrange your content, or look into a pure JavaScript solution.Alexisaley
@Jason Berkan: I now did like described here: https://mcmap.net/q/665689/-how-to-avoid-invalidoperationexception-when-setting-the-defaultbutton-in-aspx-contentCelebrate
L
8

No panel is needed. Just use the following:

UseSubmitBehavior="false"
Lipkin answered 8/2, 2014 at 18:40 Comment(0)
C
0

Please use

idTextBoxFA.Attributes.Add("onkeypress", "javascript:var evnt = window.event";
if(evnt.keyCode==13)
{
document.getElementById('" + noEnterButton.ClientID + "').click();
}
else{};");
Carcassonne answered 20/2, 2014 at 9:23 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.