Question

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

How is this possible? Does it require a plugin?

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

I wanted to know if anyone knows if there are browser issues with that command - like are there any browser compatibility issues I should know about?

Was it helpful?

Solution

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!');
    }
});

OTHER TIPS

I wrote a small plugin to make it easier to bind the "on enter key pressed" a 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 couldn't get the code posted by @Paolo Bergantino to work but when I changed it to $(document) and e.which instead of e.keyCode then I found it to work faultlessly.

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

Link to example on JS Bin

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');    
    }
});

You can do this using the jquery 'keydown' event handle

   $( "#start" ).on( "keydown", function(event) {
      if(event.which == 13) 
         alert("Entered!");
    });

I spent sometime coming up with this solution i hope it helps someone.

$(document).ready(function(){

  $('#loginforms').keypress(function(e) {
    if (e.which == 13) {
    //e.preventDefault();
    alert('login pressed');
    }
  });

 $('#signupforms').keypress(function(e) {
    if (e.which == 13) {
      //e.preventDefault();
      alert('register');
    }
  });

});

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

Use event.key and modern JS!

$(document).keypress(function(event) {
    if (event.key === "Enter") {
        // Do something
    }
});

or without jQuery:

document.addEventListener("keypress", function onEvent(event) {
    if (event.key === "Enter") {
        // Do something better
    }
});

Mozilla Docs

Supported Browsers

A minor extension of Andrea's answer above makes the helper method more useful when you may also want to capture modified enter presses (i.e. ctrl-enter or shift-enter). For example, this variant allows binding like:

$('textarea').enterKey(function() {$(this).closest('form').submit(); }, 'ctrl')

to submit a form when the user presses ctrl-enter with focus on that form's textarea.

$.fn.enterKey = function (fnc, mod) {
    return this.each(function () {
        $(this).keypress(function (ev) {
            var keycode = (ev.keyCode ? ev.keyCode : ev.which);
            if ((keycode == '13' || keycode == '10') && (!mod || ev[mod + 'Key'])) {
                fnc.call(this, ev);
            }
        })
    })
}

(see also Ctrl+Enter jQuery in TEXTAREA)

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.

Try this to detect the Enter key pressed.

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

See demo @ detect enter key press on keyboard

Using keypress method to detect pressing Enter on keyboard using jQuery?

https://www.tutsmake.com/jquery-keypress-event-detect-enter-key-pressed/

        $('#someTextBox').keypress(function(event){
            var keycode = (event.keyCode ? event.keyCode : event.which);
            if(keycode == '13'){
                alert('You pressed a "enter" key in textbox'); 
            }
            event.stopPropagation();
        });
    
<html>
<head>
<title>jQuery keypress() Method To Detect Enter key press or not Example</title> 
<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
</head>
<body>
    <h1>Write something here & press enter</h1>
    <label>TextBox Area: </label>
    <input id="someTextBox" type="text" size="100" />
 
</body>
</html>

The easy way to detect whether the user has pressed enter is to use key number the enter key number is =13 to check the value of key in your device

$("input").keypress(function (e) {
  if (e.which == 32 || (65 <= e.which && e.which <= 65 + 25)
                    || (97 <= e.which && e.which <= 97 + 25)) {
    var c = String.fromCharCode(e.which);
    $("p").append($("<span/>"))
          .children(":last")
          .append(document.createTextNode(c));
  } else if (e.which == 8) {
    // backspace in IE only be on keydown
    $("p").children(":last").remove();
  }
  $("div").text(e.which);
});

by pressing the enter key you will get result as 13 . using the key value you can call a function or do whatever you wish

        $(document).keypress(function(e) {
      if(e.which == 13) {
console.log("User entered Enter key");
          // the code you want to run 
      }
    });

if you want to target a button once enter key is pressed you can use the code

    $(document).bind('keypress', function(e){
  if(e.which === 13) { // return
     $('#butonname').trigger('click');
  }
});

Hope it help

I think the simplest method would be using vanilla javacript:

document.onkeyup = function(event) {
   if (event.key === 13){
     alert("enter was pressed");
   }
}
$(function(){
  $('.modal-content').keypress(function(e){
    debugger
     var id = this.children[2].children[0].id;
       if(e.which == 13) {
         e.preventDefault();
         $("#"+id).click();
       }
   })
});
$(document).keyup(function(e) {
    if(e.key === 'Enter') {
        //Do the stuff
    }
});
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top