Alex F Alex F - 1 month ago 8
HTML Question

Triggering JavaScript function tied to an HTML button by pressing Enter. (Without using Tab key)

My intention is to create a button which can trigger JavaScript funciton (alert "Button works!") tied to it by pressing Enter key. But it works only after using Tab key to highlight the button. I have unsuccessfully tried JavaScript and JQuery solutions. How can I make it work without fiddling around with Tab key? Here is the code:

<html>
<head>
<title>Enter Press Test</title>
</head>
<body>

<p style="text-align: center;" >

<button id="button1" onclick="alert('Button works!');" onkeypress="handle(event)">
Start Test
</button>
</p>

<!--<script type="text/javascript">
function handle(e) { // JavaScript solution
if (e.keyCode === 13) {
alert("Button works!");
}
}
</script>-->

<script type="text/javascript">
$("#button1").keyup(function(event) { // JQuery solution
if (event.keyCode == 13) {
$("#button1").click();
}
});
</script>

<script type="text/javascript" scr='./scritps/jquery-3.1.1.min.js'></script>

</body>
</html>

Answer

Add your event listener to the document element instead of #button1:

$(document).keyup(function(event) {
  if (event.keyCode == 13) {
    $("#button1").click();
  }
});

$('#button1').click(function(){
   alert('Button works!');
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<html>

<head>
  <title>Enter Press Test</title>
</head>

<body>

  <p style="text-align: center;">

    <button id="button1">
      Start Test
    </button>
  </p>

</body>

</html>