Q:

How to detect enter key press on keyboard using jQuery

0

How to detect enter key press on keyboard using jQuery

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

Use the key code 13 for Enter key

There are certain situations when you want to check whether user has pressed Enter key on keyboard, for example sending form data through Ajax on pressing Enter key, and so on.

To do this, you can simply use the key code 13, which is the ASCII equivalent of Enter key and supported in all major browsers. Let's try out an example to understand how it works:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Check if Enter Key is Pressed with jQuery</title>
<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
<script>
    $(document).on("keypress", function(e){
        if(e.which == 13){
            $("body").append("<p>You've pressed the enter key!</p>");
        }
    });
</script>
</head>
<body>
    <p><strong>Note:</strong> Click on the viewport and press the Enter key on the keyboard. A message will be displayed.</p>
</body>
</html>

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

JavaScript / jQuery Frequently Asked Questions

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
How to detect if enter key is pressed in a text in... >>
<< How to get element by class name in JavaScript...