简体   繁体   English

如何通过按Enter触发功能?

[英]how to trigger a function by pressing enter?

I have this button that leads to a method in javascript that filters the information of a table: 我有此按钮可导致javascript中的一种方法来过滤表格信息:

<button type="button" id="search" title="Buscar" onclick="fn_cliente.filtraInformacion();"></button>

There are several fields for which you can filter the information, I want that when pressing "enter" on any input, it executes the same method as when clicking on the button 有几个字段可以过滤信息,我希望在任何输入上按“输入”时,它执行与单击按钮时相同的方法

Use the following to bind the enter event to your search fields. 使用以下命令将enter事件绑定到您的搜索字段。

document.querySelectorAll('.searchfield').forEach(function(input) {
  input.addEventListener('keypress', function(e) {
    if (e.keyCode === 13) filtraInformacion();
  });
});

Look at this code snippet 看看这个代码片段

 function filtraInformacion() { console.log('filtraInformacion has been called!'); } document.querySelectorAll('.searchfield').forEach(function(input) { input.addEventListener('keypress', function(e) { if (e.keyCode === 13) filtraInformacion(); }); }); 
 <button type="button" id="search" title="Buscar" onclick="filtraInformacion();">Click me</button> <br> <input id='name' class='searchfield' placeholder='Press Enter!'> <br> <input id='lastname' class='searchfield' placeholder='Press Enter!'><br> <input id='gender' class='searchfield' placeholder='Press Enter!'> 

See? 看到? when the enter key is pressed, the function filtraInformacion is called. 当按下回车键时,将调用filtraInformacion函数。

This works. 这可行。 You can adapt it to whatever element you want. 您可以将其调整为所需的任何元素。

<input type="text" id="account-location-country-input" class="mdc-text-field__input" required onkeyup = "if (event.keyCode == 13)document.getElementById('edit-account-button').click()">

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

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