当基于哪个文本框具有焦点时,按下Enter键时如何触发Button Click事件?
我有一个带有多个提交按钮的表单.我希望根据当前具有焦点的文本框按下Enter键时触发按钮的单击事件.通过将onkeydown事件添加到页面正文并检查Enter的keyCode,我可以使用下面的代码指定一个按钮
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>
我假定可以修改此代码或调用一个函数以执行条件以查看txtSearch或txtSubmit是否具有焦点并相应地指定btnSearch或btnSubmit,但是我对Java没有经验.
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!
我终于得到了我想要的结果.我需要使用一个函数来停止触发默认的输入"按钮,并使用另一个函数来触发正确的按钮的单击事件.这是使用的脚本:
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:
<script type="text/javascript">
function KeyDownEventHandler(e, box) {
var charCode = (e.which) ? e.which : event.keyCode
if (charCode == 13)
document.getElementById(box).click();
}
function DisableEnterKey() {
if (event.keyCode == 13) {
return false;
}
else {
return true;
}
}
</script>
我从主体的onkeydown事件中调用了DisableEnterKey函数,并从文本框的onkeydown事件中调用了KeyDownEventHandler:
I called the DisableEnterKey function from the body's onkeydown event and the KeyDownEventHandler from the textbox's onkeydown event:
<body onkeydown="return DisableEnterKey()">
...
<input id="txtSearch" type="text" runat="server" onkeydown="KeyDownEventHandler(event, 'btnSearch');" />
...
<input id="txtAddEor" type="text" runat="server" onkeydown="KeyDownEventHandler(event, 'btnAddEor');" />
...
<input id="txtCategory" type="text" runat="server" onkeydown="KeyDownEventHandler(event, 'btnAddEor');" />