当基于哪个文本框具有焦点时,按下Enter键时如何触发Button Click事件? [英] How can I fire a Button Click event when Enter Key is pressed based on what textbox has focus?

查看:180
本文介绍了当基于哪个文本框具有焦点时,按下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');" />

这篇关于当基于哪个文本框具有焦点时,按下Enter键时如何触发Button Click事件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆