javascript – Place button click on Enter key

Question:

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

Answer:

You have to set an event listener for when a key is pressed:

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

And then check if the key was Enter :

if(e.which == 13)

Example (with an event handler for 3 buttons to check it's the right one):

$(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>
Scroll to Top