jQuery Keycode Examples ( Enter button | Escape button )
Have you ever wanted to use Enter and Escape button functionality for form submission, etc.? In this article, I am going to discuss an easy way to do it using Enter Keycode and Escape Keycode in jQuery.
Examples for Enter Keycode & Escape Keycode using jQuery
When you run the following code, you will see the text “This is some text.”. Hit “Enter” on your keyboard and you will see the alert: “Enter button was pressed!”. If you hit Escape button on your keyboard, you will see the alert: “Escape button was pressed!”.
Example 1: Using button keycodes in jQuery
<html>
<head>
<title>jQuery Keycode Examples for Enter button and Escape Button</title>
<script type="text/javascript" src="js/jquery_1.7.1_min.js"></script>
</head>
<body>
Hit Enter on your keyboard.<br/>
Hit Escape button on your keyboard.
<script type="text/javascript">
$(document).keyup(function(e) {
//Enter
if (e.keyCode == 13)
{
alert('Enter button was pressed!');
}
//Escape
if (e.keyCode == 27)
{
alert('Ecape button was pressed!');
}
});
</script>
</body>
</html>Example 2: Using button keycodes in jQuery
You can now extend this code for form submission or cancellation, like so:
<script type="text/javascript">
$(document).keyup(function(e) {
//Enter
if (e.keyCode == 13)
{
$('#save').click();
}
//Escape
if (e.keyCode == 27)
{
$('#cancel').click();
}
});
</script>In the above example, #save refers to the ID of the Save button in a form and #cancel refers to the ID of the Cancel button in the same form. So now when you hit Enter / Cancel buttons, they perform the same action as your Save and Cancel buttons respectively as it simulates click event on those buttons.
That’s it!
Do you know of any other practical uses of Enter Keycode and Escape Keycode in jQuery? Feel free to share by commenting below.