By default, when the Enter
key is pressed in a form's input field, it will trigger the form to be submitted.
This behaviour can be prevented with JavaScript — here's how:
- Listen for key presses in the input using the
keydown
event. - Check the key pressed by reading the
key
property of the event object. - If the key is
Enter
, prevent the default behaviour (triggering form submit) by callingpreventDefault
method on the event object.
For example:
<form>
<input type="text" placeholder="Type message" />
</form>
<script>
document.querySelector('input')
.addEventListener('keydown', (e) => {
if (e.key === 'Enter') {
e.preventDefault();
}
});
</script>
This way, every time Enter
is pressed in the form's input field, the form won't be submitted.
Top comments (0)