How to Handle Keyup Event Using jQuery
Handling a keyup event in jQuery allows you to trigger
specific actions when a user releases a key on the keyboard. This
article provides a concise guide to implementing keyup listeners using
jQuery's built-in .keyup() shortcut and the versatile
.on() method, showing you how to capture input values and
detect specific keys.
Using the .keyup()
Method
The most straightforward way to listen for a key release is using
jQuery’s .keyup() event handler. You attach this method to
a target element, such as an input field or the whole document.
$('#search-input').keyup(function() {
let currentValue = $(this).val();
console.log("Current input value: " + currentValue);
});In this example, every time a user releases a key inside the
#search-input element, the anonymous function executes and
logs the current value of the field.
Using the
.on('keyup', handler) Method
The modern and preferred approach in jQuery is using the
.on() method. It provides greater flexibility, including
the ability to bind multiple events and handle event delegation for
dynamically generated elements.
// Direct event binding
$('#search-input').on('keyup', function() {
console.log("Key released.");
});
// Delegated event binding (useful for elements added dynamically)
$(document).on('keyup', '.dynamic-input', function() {
console.log("Key released in a dynamically added element.");
});Detecting Specific Keys
To detect which key was pressed and released, pass the event object
to your callback function. Modern browsers support the
event.key property, which returns the name of the pressed
key (such as "Enter", "Escape", or
"a").
$('#search-input').on('keyup', function(event) {
if (event.key === 'Enter') {
alert('Enter key was pressed!');
}
});If you need backward compatibility with older browsers, you can use
event.which or event.keyCode to inspect the
numeric ASCII value of the key:
$('#search-input').on('keyup', function(event) {
// 13 is the key code for the Enter key
if (event.which === 13) {
alert('Enter key pressed via keyCode.');
}
});Removing a Keyup Handler
To stop listening for the keyup event, you can use the
.off() method:
$('#search-input').off('keyup');