Get the value of input text when enter key pressed

Learn get the value of input text when enter key pressed with practical examples, diagrams, and best practices. Covers javascript, html, input development techniques with visual explanations.

Capture Input Text on Enter Key Press in JavaScript

Hero image for Get the value of input text when enter key pressed

Learn how to efficiently retrieve the value from an HTML input field when a user presses the Enter key, a common requirement for forms and search bars.

In web development, it's a frequent task to capture user input from a text field. While a 'submit' button is one way to do this, many applications, especially search interfaces or chat applications, require the input to be processed immediately when the user presses the Enter key. This article will guide you through the JavaScript techniques to detect the Enter key press and extract the input field's value.

Understanding Keyboard Events

JavaScript provides several event listeners for keyboard interactions. The most relevant for detecting key presses are keydown, keypress, and keyup. While keypress was traditionally used, it's now largely deprecated and keydown or keyup are preferred. For our purpose, keydown is ideal because it fires as soon as the key is pressed down, allowing for immediate action.

flowchart TD
    A[User types in input field] --> B{Key Pressed?}
    B -- Yes --> C{Is it 'Enter' key?}
    C -- Yes --> D[Get input value]
    C -- No --> E[Do nothing / Other action]
    D --> F[Process value]
    E --> B
    F --> B

Flowchart of detecting and processing Enter key press

Implementing the Event Listener

To capture the Enter key press, you'll need to select your input element, attach an event listener for the keydown event, and then check the event.key or event.keyCode (for older browsers) property within the event handler function. The event.key property is the modern and recommended way to identify the key, returning a string like 'Enter', 'Escape', 'a', '1', etc. The event.keyCode property returns a numeric value, with 13 being the code for the Enter key.

<input type="text" id="myInput" placeholder="Type something and press Enter">

Basic HTML input element

document.addEventListener('DOMContentLoaded', function() {
    const inputElement = document.getElementById('myInput');

    inputElement.addEventListener('keydown', function(event) {
        // Check if the pressed key is 'Enter'
        if (event.key === 'Enter') {
            // Prevent the default action (e.g., form submission if inside a form)
            event.preventDefault(); 
            
            const inputValue = inputElement.value;
            console.log('Input value on Enter:', inputValue);
            
            // Optionally, clear the input field after capturing
            // inputElement.value = '';
        }
    });
});

JavaScript code to capture input value on Enter key press

Cross-Browser Compatibility (Legacy Support)

While event.key is widely supported in modern browsers, if you need to support very old browsers, you might consider using event.keyCode or event.which. However, for most contemporary web development, event.key is sufficient and more readable. The keyCode for the Enter key is 13.

document.addEventListener('DOMContentLoaded', function() {
    const inputElement = document.getElementById('myInput');

    inputElement.addEventListener('keydown', function(event) {
        // Modern approach: event.key
        // Legacy approach: event.keyCode === 13
        if (event.key === 'Enter' || event.keyCode === 13) {
            event.preventDefault(); 
            const inputValue = inputElement.value;
            console.log('Input value on Enter (legacy check):', inputValue);
        }
    });
});

Including legacy keyCode check for broader compatibility

1. Create an HTML Input Field

Add an <input type="text"> element to your HTML document and give it a unique id for easy selection in JavaScript.

2. Select the Element in JavaScript

Use document.getElementById() to get a reference to your input element.

3. Attach a keydown Event Listener

Add an event listener to the input element for the keydown event. This listener will execute a function every time a key is pressed while the input is focused.

4. Check for the Enter Key

Inside the event handler function, check if event.key is equal to 'Enter'. Optionally, include event.keyCode === 13 for older browser support.

5. Prevent Default Behavior

Call event.preventDefault() to stop any default browser actions associated with the Enter key, such as submitting a form.

6. Retrieve Input Value

Access the input field's value using inputElement.value and then process it as needed.