Click on the Enter key

Asked

Viewed 24,802 times

7

Could someone help me put the button click on the key Enter using Javascript or Jquery?

2 answers

16


You must select an event receiver for when a key is pressed:

$(document).keypress(function(e) {

And then check if the key was the Enter:

if(e.which == 13)

Example (with an Event Handler for 3 buttons to verify that it is correct):

$(document).keypress(function(e) {
    if(e.which == 13) $('#meuBotao').click();
});

$('button').click(function(e) {
    alert(this.innerHTML);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button>Botão 1</button>
<button id="meuBotao">Botão 2</button>
<button>Botão 3</button>

  • @Marconi 53? (Glad I could help!)

  • @Marconi works for me. Click on "run code snippet" and press `Enter". For me it gives the Alert from button 2, in Chrome.

2

I believe that there is no need to give an example with jquery for this purpose. Then follows below an example with pure Js.

To listen to DOM events (browser page), just use the addEventListener('event', callback, false), the code below will do what you requested:

document.addEventListener('keypress', function(e){
       if(e.which == 13){
          console.log('a tecla enter foi pressionada');
       }
    }, false);

Well, reviewing what you requested, you must be wanting to send some form information, no?

Let’s say, you can create a function for this purpose and run within the Systener, example:

document.addEventListener('keypress', function(e){
  if(e.which == 13){
    enviaForm();
  }
}, false);

function enviaForm(){
  var nome = document.querySelector('#nome');
  var email = document.querySelector('#email');
  var password = document.querySelector('#password');
};

I hope it helped.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.