Detect when Enter is pressed within an Input Element

Published: 2019-10-14 10:37:16 +0000
Categories: Javascript,




If a user presses enter on an input field in a HTML form, then by default the browser will seek out the first submit button within the parent form and then trigger that (essentially simulating the click).

In today's Javascript heavy world though, it may be that your <input> doesn't sit within a <form> and you instead want to replicate the behaviour.

This javascript snippet attaches an event handler to an element in order to detect when the Enter key is pressed within that element - most usually a text input, but it should work on any input


node.addEventListener("keyup", function(event) {
    if (event.key === "Enter") {
        // Do stuff

Usage Example

<input id="somefield">

<script type="text/javascript">
document.getElementById('somefield').addEventListener("keyup", function(event) {
    if (event.key === "Enter") {
        alert('Submitted with ' + event.srcElement.value);


js, return, enter, keypress, keyup, event,

Latest Posts

Copyright © 2022 Ben Tasker | Sitemap | Privacy Policy
Available at, http://phecoopwm6x7azx26ctuqcp6673bbqkrqfeoiz2wwk36sady5tqbdpqd.onion and http://snippets.bentasker.i2p
hit counter