简体   繁体   English

Javascript:输入按键

[英]Javascript : Enter Key Press

Good Morning... 早上好...

I am using java script in each page to trigger the Enter key press Event inside the textbox. 我在每个页面中使用java脚本来触发文本框内的Enter键按事件。 It is working fine. 它工作正常。 Now i want to place the code in the .js file for global access. 现在我想将代码放在.js文件中以进行全局访问。

 function EnterKeyPress(id,e) {
       // look for window.event in case event isn't passed in
       if (window.event) { e = window.event; }
       if (e.keyCode == 13 || e.keyCode == 121) {

           window.document.getElementById('<%= ibtnSubmit.ClientID %>').click();
       } 
   }

I dont want to hard code the control id. 我不想硬编码控件ID。 Can anybody help me please.. 有人可以帮帮我吗

You can use your id parameter instead of the ControlID, and when you use this function in your pages, you can pass the ControlID as a parameter: 您可以使用id参数而不是ControlID,并且在页面中使用此功能时,可以将ControlID作为参数传递:

function EnterKeyPress(id,e) {
  if (window.event) { e = window.event; }
   if (e.keyCode == 13 || e.keyCode == 121) {
     document.getElementById(id).click();
   }
}

You are using ASP .NET, so in your code-behind you can assign the keypress event: 您正在使用ASP .NET,因此在您的代码隐藏中,您可以分配keypress事件:

TextBox1.Attributes.Add("onkeypress",
                      string.Format("EnterPressKey('{0}', event);", ibtnSubmit.ClientID));

But wait, that functionality is already done on ASP .NET, you can use ASP:Panel controls to wrap your common controls, and you can assign a DefaultButton for the panel to indicate which button gets clicked when the Panel control has focus and the user presses the Enter key. 但是等等,该功能已经在ASP .NET上完成,您可以使用ASP:Panel控件来包装您的常用控件,并且您可以为面板指定DefaultButton以指示当Panel控件具有焦点时用户单击哪个按钮以及用户按Enter键。

如果你正在使用jQuery,你可以这样做:

$("input[id*=ibtnSubmit]").click()

If you want the form to submit when the user presses the Enter key, then you don't need javascript. 如果您希望在用户按Enter键时提交表单,则您不需要javascript。 It will do so automatically. 它会自动完成。 Just put the textbox inside a form element with an action: 只需将文本框放在带有操作的表单元素中:

<form action="process.php">
  <input type="text">when the enter key is pressed, the form is submitted and sent to process.php</input>
</form>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM