How can I detect pressing Enter on the keyboard using jQuery?

Viewed 963157

I would like to detect whether the user has pressed Enter using jQuery.

How is this possible? Does it require a plugin?

It looks like I need to use the keypress() method.

Are there browser issues with that command - like are there any browser compatibility issues I should know about?

19 Answers

The whole point of jQuery is that you don't have to worry about browser differences. I am pretty sure you can safely go with enter being 13 in all browsers. So with that in mind, you can do this:

$(document).on('keypress',function(e) {
    if(e.which == 13) {
        alert('You pressed enter!');
    }
});

I wrote a small plugin to make it easier to bind the "on enter key pressed" event:

$.fn.enterKey = function (fnc) {
    return this.each(function () {
        $(this).keypress(function (ev) {
            var keycode = (ev.keyCode ? ev.keyCode : ev.which);
            if (keycode == '13') {
                fnc.call(this, ev);
            }
        })
    })
}

Usage:

$("#input").enterKey(function () {
    alert('Enter!');
})

I found this to be more cross-browser compatible:

$(document).keypress(function(event) {
    var keycode = event.keyCode || event.which;
    if(keycode == '13') {
        alert('You pressed a "enter" key in somewhere');    
    }
});

There's a keypress() event method. The Enter key's ASCII number is 13 and is not dependent on which browser is being used.

In some cases, you may need to suppress the ENTER key for a certain area of a page but not for other areas of a page, like the page below that contains a header <div> with a SEARCH field.

It took me a bit to figure out how to do this, and I am posting this simple yet complete example up here for the community.

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
  <title>Test Script</title>
  <script src="/lib/js/jquery-1.7.1.min.js" type="text/javascript"></script>
  <script type="text/javascript">
    $('.container .content input').keypress(function (event) {
      if (event.keyCode == 10 || event.keyCode == 13) {
        alert('Form Submission needs to occur using the Submit button.');
        event.preventDefault();
      }
    });
  </script>
</head>
  <body>
    <div class="container">
      <div class="header">
        <div class="FileSearch">
          <!-- Other HTML here -->
        </div>
      </div>
      <div class="content">
        <form id="testInput" action="#" method="post">
        <input type="text" name="text1" />
        <input type="text" name="text2" />
        <input type="text" name="text3" />
        <input type="submit" name="Submit" value="Submit" />
        </form>
      </div>
    </div>
  </body>
</html>

Link to JSFiddle Playground: The [Submit] button does not do anything, but pressing ENTER from one of the Text Box controls will not submit the form.

As the keypress event isn't covered by any official specification, the actual behavior encountered when using it may differ across browsers, browser versions, and platforms.

$(document).keydown(function(event) {
  if (event.keyCode || event.which === 13) {
    // Cancel the default action, if needed
    event.preventDefault();
    // Call function, trigger events and everything you want to do. Example: Trigger the button element with a click
    $("#btn").trigger('click');
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<button id="btn" onclick="console.log('Button Pressed.')">&nbsp</button>

I used $(document).on("keydown").

On some browsers keyCode is not supported. The same with which so if keyCode is not supported you need to use which and vice versa.

$(document).on("keydown", function(e) {
  const ENTER_KEY_CODE = 13;
  const ENTER_KEY = "Enter";
  var code = e.keyCode || e.which
  var key = e.key
  if (code == ENTER_KEY_CODE || key == ENTER_KEY) {
    console.log("Enter key pressed")
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>

$(document).keydown(function (event) {
      //proper indentiation of keycode and which to be equal to 13.
    if ( (event.keyCode || event.which) === 13) {
        // Cancel the default action, if needed
        event.preventDefault();
        //call function, trigger events and everything tou want to dd . ex : Trigger the button element with a click
        $("#btnsearch").trigger('click');
    }
});
$(document).keyup(function(e) {
    if(e.key === 'Enter') {
        //Do the stuff
    }
});

This my how I solved it. You should use return false;

$(document).on('keypress', function(e) {
    if(e.which == 13) {
        $('#sub_btn').trigger('click');
        alert('You pressed the "Enter" key somewhere');
        return false;
    }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<form action="" method="post" id="sub_email_form">
    <div class="modal-header">
        <button type="button" class="close" id="close" data-dismiss="modal">&times;</button>
        <h4 class="modal-title">Subscribe to our Technical Analysis</h4>
    </div>
    <div class="modal-body">
        <p>Signup for our regular Technical Analysis updates to review recommendations delivered directly in your inbox.</p>
        <div class="input-group">
            <input type="email" name="sub_email" id="sub_email" class="form-control" placeholder="Enter your email" required>
        </div>
        <span id="save-error"></span>
    </div>
    <div class="modal-footer">
        <div class="input-group-append">
            <input type="submit" class="btn btn-primary sub_btn" id="sub_btn" name="sub_btn" value="Subscribe">
        </div>
    </div>
</form>

$(function(){
  $('.modal-content').keypress(function(e){
    debugger
     var id = this.children[2].children[0].id;
       if(e.which == 13) {
         e.preventDefault();
         $("#"+id).click();
       }
   })
});
Related