Place button click Enter

5

Can one help me put the button on the Enter button using Javascript or Jquery ?

    
asked by anonymous 22.12.2014 / 11:59

2 answers

12

You need to define an event sink for when a key is pressed:

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

And then verify that the key was 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ão1</button><buttonid="meuBotao">Botão 2</button>
<button>Botão 3</button>
    
22.12.2014 / 12:03
2

I do not think you need to give an example with jquery for this purpose. Then follows an example with pure Js.

To listen for DOM events (browser page), just use 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 should be wanting to send some form information, right?

Let's say it is, you can create a function for this purpose and run within the listener, 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 you have helped.

    
24.12.2014 / 18:21