javascript 如何检查是否在 asp.net 的 TextBox 中按下了 Enterkey

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7835453/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 01:28:52  来源:igfitidea点击:

How to check if enterkey is pressed in a TextBox in asp.net

c#javascriptjqueryasp.net

提问by James

I have a asp.net Text Box which accepts date in the format MM/DD/YYYY. After entering the date i will hit enter key.if enter key i need to execute server side code.How can we achieve this ?

我有一个 asp.net 文本框,它接受格式为 MM/DD/YYYY 的日期。输入日期后,我将按回车键。如果回车键,我需要执行服务器端代码。我们怎样才能做到这一点?

The problem with Text box is it will fire the Text Changed event only if it looses the focus.

文本框的问题是它只有在失去焦点时才会触发 Text Changed 事件。

回答by Ricardo Binns

you set jquery tag

你设置 jquery 标签

so using jquery u can try something like this

所以使用 jquery 你可以尝试这样的事情

$("#field").keydown(function(e){
     if(e.keyCode === 13)
     {
          // enter event
     }
});

回答by James

You can use the Panel.DefaultButtonproperty to automatically click a button when the user presses Enter.

您可以使用Panel.DefaultButton属性在用户按下 Enter 键时自动单击按钮。

For example:

例如:

<asp:Panel Id="panel1" runat="server" DefaultButton="btnSubmit">
  <asp:TextBox Id="txtDate" runat="server" />
  <asp:Button Id="btnSubmit" Text="Submit" OnClick="btnSubmit_Click" runat="server" />
</asp:Panel>

If you don't want to show the button, you can set its style="display: none".

如果不想显示按钮,可以设置它的style="display: none".

回答by Saul

Use the keydown event:

使用 keydown 事件:

textBox.Attributes.Add("onKeyDown", "KeyDownHandler()");

Have KeyDownHandler()check the pressed key and if correct, submit the surrounding form or invoke an AJAX request. See keyboard codes at Javascript Char Codes.

KeyDownHandler()检查的按键,如果正确,提交周围的形式或调用Ajax请求。请参阅Javascript 字符代码中的键盘代码。



Alternatively, textbox ID can be injected into jQuery from .aspxand assigned a direct keydown handler:

或者,文本框 ID 可以从 jQuery 注入.aspx并分配一个直接的 keydown 处理程序:

$('#<%=textBox.clientID%>').keydown(function (e) { /* Do server request; */ });

回答by HashimR

You can call this Javascript function to check whether enter key has been pressed or not.

您可以调用此 Javascript 函数来检查是否已按下 Enter 键。

function checkEnterKeyPress(e)
{
     var key;     
     if(window.event)
          key = window.event.keyCode; //IE
     else
          key = e.which; //firefox     

     if (key == 13){
         alert(key);
     }
}