简体   繁体   English

按输入控件外输入键时如何触发按钮单击

[英]How to trigger button click when press enter key outside of input controls

I have several html input controls on a page and a search button. 我在页面上有几个html input控件和一个搜索按钮。 When user is outside the input controls, ( ie focus is not inside the input control) and if user press enter, i want to trigger click event of search button. 当用户在输入控件之外时(即焦点不在输入控件内),如果用户按回车键,我想触发搜索按钮的点击事件。 The search button is not a Submit button and it is not inside a form 搜索按钮不是“ Submit按钮,它不在form

<input type="text" id="input1" />
<input type="checkbox" id="input2" />
<input type="text" class="autocomplete" id="input3" />

<button type="button" id="btnSearch">Search</button>

currently I am doing this 目前我正在这样做

$(document).keypress(function (event) {
    if (event.keyCode === 13) {
        $("#btnSearch").click();
    }
})

However, the above code triggers click event every time user clicks enter. 但是,上述代码会在用户单击enter时触发click事件。

Some of the input controls I have are custom autocomplete controls. 我有一些输入控件是自定义自动完成控件。 Auto complete control shows multiple options as soon user starts typing something. 用户开始输入内容后,自动完成控制会显示多个选项。 Then user can select the option by using mouse or by pressing enter. 然后,用户可以使用鼠标或按Enter键选择该选项。

I don't want to trigger the click event of a search button when user press enter to select an option. 当用户按Enter键选择选项时,我不想触发搜索按钮的click事件。

Just make sure that the autocomplete element isn't the source of the enter press. 只需确保autocomplete元素不是enter press的来源。 From the demo you give in your question, this will work. 从您在问题中提供的演示中,这将有效。 However, if it is slightly different in your use case, you may need to adjust the class name or selector to make sure it is preventing the correct target element 但是,如果在您的用例中略有不同,您可能需要调整类名称或选择器以确保它阻止正确的目标元素

 $(document).keypress(function (event) { if (event.keyCode === 13 && !$(event.target).hasClass("autocomplete")) { $("#btnSearch").click(); alert('btnSearchClick'); } }) 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <input type="text" id="input1" /> <input type="checkbox" id="input2" /> <input type="text" class="autocomplete" id="input3" /> <button type="button" id="btnSearch">Search</button> 

Alternatively, since events propagate out, if you can prevent the propagation of the autocomplete event in whichever library you are using, that may work as well. 或者,由于事件传播出去,如果您可以阻止自动完成事件在您使用的任何库中传播,那么这也可能有效。

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

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