当按下 Enter 键时,如何根据具有焦点的文本框触发按钮单击事件?
我有一个带有几个提交按钮的表单。我希望根据当前具有焦点的文本框按下 Enter 键时触发按钮的单击事件。我可以使用下面的代码指定一个按钮,方法是将 onkeydown 事件添加到页面正文并检查 Enter 的 keyCode
<body onkeydown="if(event.keyCode==13){document.getElementById('btnSearch').click();}">
...
</body>
我假设可以修改此代码或调用函数来执行条件以查看 txtSearch 或 txtSubmit 是否具有焦点并相应地指定 btnSearch 或 btnSubmit,但我对 javascript 没有经验。
任何帮助/建议都会很棒!
I have a form with several submit buttons. I would like the button's click events to fire when enter is pressed based on which textboxes currently have focus. I am able to specify one button using the code below by adding the onkeydown event to the body of the page and checking for Enter's keyCode
<body onkeydown="if(event.keyCode==13){document.getElementById('btnSearch').click();}">
...
</body>
I assume this code can be modified or call a function to perform a conditional to see if txtSearch or txtSubmit has focus and specify btnSearch or btnSubmit accordingly, but I am not experienced with javascript.
Any help/advice would be great!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您可以使用 asp:Panel 控件来帮助您完成此操作。 asp:Panel 有“DefaultButton”,您可以在其中指定按钮的 ID。
http://msdn.microsoft. com/en-us/library/system.web.ui.webcontrols.panel.defaultbutton.aspx
它可能不完全是您所需要的,但它始终足以满足我的需求。
希望这对您有帮助。
问候
You can use asp:Panel controls to help you with this. An asp:Panel has "DefaultButton" where you specify a button's ID.
http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.panel.defaultbutton.aspx
It might not be exactly what you need, but it has always been enough for my needs.
Hope this helps you.
Regards
第一个问题可能只是一个拼写错误,但您需要在上面的代码中添加单引号并删除分号。
但我不认为捕获全局按键事件是最好的方法。我会将 onkeydown 添加到实际的表单控件中,这样您就不会只是拾取每个输入。此外,您还可以在事件处理程序方法调用中指定一个参数来指示正在使用哪个文本框。
然后,您只需编写处理所有按键捕获事件的方法:
我更改了按键代码检测以更好地与其他浏览器配合使用。
The first problem might just be a typo but you need to add a single quote and remove the semi-colon in your code above.
But I don't think capturing a global key down event is the best way to go. I would add the onkeydown to the actual form controls so you aren't just picking up every enter. Also doing that you can specify in the event handler method call a parameter that indicates which textbox is being used.
Then you just write the method to handle all the key capture events:
I changed the keycode detection to better work with other browsers.
我终于得到了我想要的结果。我需要使用一个函数来阻止默认的“输入”按钮触发,并使用另一个函数来触发正确按钮的单击事件。这是使用的脚本:
我从正文的 onkeydown 事件调用了 DisableEnterKey 函数,并从文本框的 onkeydown 事件调用了 KeyDownEventHandler:
I finally got the results I was after. I needed to use a function to stop the default 'enter' button from firing and another function to fire the correct button's click event. Here is the script used:
I called the DisableEnterKey function from the body's onkeydown event and the KeyDownEventHandler from the textbox's onkeydown event: