Detect when Enter is pressed within an Input Element (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
Details
- Language: Javascript
Snippet
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);
}
});`
</script>