简体   繁体   中英

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:

<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.

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.

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()">

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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