enter key in asp.net firing wrong button

2020-05-25 06:12发布

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?

3条回答
萌系小妹纸
2楼-- · 2020-05-25 06:46

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>
查看更多
神经病院院长
3楼-- · 2020-05-25 06:48

No panel is needed. Just use the following:

UseSubmitBehavior="false"
查看更多
混吃等死
4楼-- · 2020-05-25 07:02

Please use

idTextBoxFA.Attributes.Add("onkeypress", "javascript:var evnt = window.event";
if(evnt.keyCode==13)
{
document.getElementById('" + noEnterButton.ClientID + "').click();
}
else{};");
查看更多
登录 后发表回答