Emmanuel Akinfulubi

JavaScriptEvents

Detect the Enter key in an input in JavaScript

Beginner · 4 min read

Chat boxes send your message when you press Enter. Search boxes start searching. To-do apps add the item you just typed. Listening for one particular key is a small job, but there are two situations where pressing Enter should do nothing, and the bugs they cause are easy to miss.

In this tutorial you will make a text box that adds what you typed to a list when Enter is pressed, then clears itself. You will use the modern way to tell keys apart and handle a held-down key and text being composed in other scripts. You should have used addEventListener and know what trim() does.

The keydown event and event.key

Pressing a key in a text box fires a keydown event on it. The event object's key property is the name of the key, as a string:

  • 'Enter', 'Escape', 'Tab', 'ArrowUp' for the special keys.
  • 'a', 'B', '7' for the character the key types.
  • ' ' (a single space) for the space bar.

You may meet older code that checks event.keyCode === 13. keyCode and which are deprecated, which means browsers keep them only so old pages don't break. They give numbers that can differ between keyboard layouts. Use event.key.

Here is the page:

index.html

<input id="box" placeholder="Type and press Enter">

Here is the exercise. Try it yourself first, or read on and we will build it.

9 Detect the Enter key in a text box

easy

Run something when Enter is pressed in a text input. Use the property that is not deprecated.

Stuck? Three hints, smallest first
  1. 1. event.key === ‘Enter’. keyCode is deprecated and which more so.
  2. 2. keydown repeats while the key is held; event.repeat tells you.
  3. 3. While composing text in another script, isComposing is true and Enter means "accept", not "submit".

Step 1: see which keys arrive

Step 1

const box = document.getElementById('box');
const seen = [];
box.addEventListener('keydown', (event) => {
  seen.push(event.key);
});
for (const key of ['a', 'Enter', ' ']) {
  box.dispatchEvent(new KeyboardEvent('keydown', { key }));
}
console.log(seen); // ['a', 'Enter', ' ']

new KeyboardEvent('keydown', { key }) fakes a key press, so you can check the handler without typing. Every key reaches the listener, so the handler has to pick out Enter itself.

Step 2: act on Enter only

Step 2

const box = document.getElementById('box');
const submitted = [];
box.addEventListener('keydown', (event) => {
  if (event.key !== 'Enter') return;
  event.preventDefault();
  const value = box.value.trim();
  if (value === '') return;
  submitted.push(value);
  box.value = '';
});
const press = (key, extra = {}) =>
  box.dispatchEvent(new KeyboardEvent('keydown', { key, cancelable: true, ...extra }));
box.value = '  Ojota to Abuja  ';
press('Enter');
console.log(submitted, JSON.stringify(box.value)); // ['Ojota to Abuja'] ""
box.value = 'Berger';
press('a');
console.log(submitted.length); // 1: a letter doesn't submit

Reading it from the top:

  • Any key that isn't Enter leaves straight away with return.
  • preventDefault() stops Enter's built-in action. If the box sits inside a form, Enter would also submit the form and reload the page.
  • trim() removes spaces at both ends, so a box of only spaces counts as empty and adds nothing.
  • The value is saved, then the box is cleared for the next entry.

press is a small helper that fakes a key press. Its extra argument lets the next steps add more details to the event.

Step 3: a key that's held down

Hold a key down and keydown fires again and again, as the key repeats. With the handler from Step 2, holding Enter would try to submit over and over. The event's repeat property is true for those repeated events, so ignore them:

Step 3

const box = document.getElementById('box');
const submitted = [];
box.addEventListener('keydown', (event) => {
  if (event.key !== 'Enter') return;
  if (event.repeat) return;
  submitted.push(box.value);
});
box.value = 'Berger';
box.dispatchEvent(new KeyboardEvent('keydown', { key: 'Enter' }));
box.dispatchEvent(new KeyboardEvent('keydown', { key: 'Enter', repeat: true }));
box.dispatchEvent(new KeyboardEvent('keydown', { key: 'Enter', repeat: true }));
console.log(submitted.length); // 1: the two repeats were ignored

This cut-down handler only shows the new line. The first press counts, and the repeats that follow while the key is held are skipped.

Step 4: text that is still being composed

People typing Chinese, Japanese or Korean, and people using some accent keys, build each character in several key presses. While they do, event.isComposing is true, and Enter means "accept this character", not "submit". If you ignore that, the form is unusable for them, and you'll never notice if you only type in English.

Here is the handler with both guards:

Step 4

const box = document.getElementById('box');
const submitted = [];
box.addEventListener('keydown', (event) => {
  if (event.key !== 'Enter') return;
  if (event.isComposing) return;
  if (event.repeat) return;
  event.preventDefault();
  const value = box.value.trim();
  if (value === '') return;
  submitted.push(value);
  box.value = '';
});
const press = (key, extra = {}) =>
  box.dispatchEvent(new KeyboardEvent('keydown', { key, cancelable: true, ...extra }));
box.value = 'Berger';
press('Enter', { repeat: true });
box.value = 'Ilorin';
press('Enter', { isComposing: true });
console.log(submitted.length); // 0: both were ignored
press('Enter');
console.log(submitted); // ['Ilorin']

The held key and the mid-composition Enter add nothing. A normal Enter afterwards adds the text.

The full solution

The panel builds the box and presses Enter in every situation. Its checks confirm Enter submits and clears the box, it cancels the default, letters don't submit, a repeating Enter and an Enter while composing are ignored, empty and space-only boxes add nothing, the value is trimmed, and keys like Escape and the space bar arrive with their names. Press Run, then type into the live demo, which shows each key's name as you press it.

Live, in a real browser. Click it. Sandboxed to allow-scripts only, so it cannot reach this page.

The answer

const box = el('input', { id: 'box', placeholder: 'Type and press Enter' });
document.body.appendChild(box);

const submitted = [];
const seen = [];

box.addEventListener('keydown', (event) => {
  seen.push(event.key);
  if (event.key !== 'Enter') return;
  if (event.isComposing) return;         // mid-composition, Enter accepts the text
  if (event.repeat) return;              // a held key repeats; act once
  event.preventDefault();
  const value = box.value.trim();
  if (value === '') return;
  submitted.push(value);
  box.value = '';
});

// The real constructor is KeyboardEvent; the stand-in copies any extra option
// onto the event, so this behaves the same way.
const press = (key, extra = {}) => {
  const event = new Event('keydown', { bubbles: true, cancelable: true, key, ...extra });
  box.dispatchEvent(event);
  return event;
};

box.value = 'Ojota to Abuja';
const enter = press('Enter');
console.log('after Enter      :', submitted, '| box cleared:', JSON.stringify(box.value));
console.log('default prevented:', enter.defaultPrevented);

box.value = 'Berger';
press('a');
console.log('after a letter   :', submitted, '<- unchanged');

box.value = 'Berger';
press('Enter', { repeat: true });
console.log('a held Enter     :', submitted, '<- ignored');

box.value = 'Ilorin';
press('Enter', { isComposing: true });
console.log('while composing  :', submitted, '<- ignored');

press('Enter');
console.log('with an empty box:', submitted, '<- nothing added');
console.log('keys seen        :', seen);
console.log('keyCode for Enter was', 13, '- deprecated, do not use it');

Output


      
13 checks that prove this answer

You do not have to read these. They are part of the answer panel above, so pressing Run there executes all 13 of them and prints ok for each. That output is the proof, and the build fails if a single check fails.

13 checks

test('Enter submits the value', submitted, ['Ojota to Abuja', 'Ilorin']);
test('and clears the box', box.value, '');
test('it cancels the default, so a form does not also submit', enter.defaultPrevented, true);
test('a letter does not submit', (() => { box.value = 'x'; const before = submitted.length; press('a'); return submitted.length - before; })(), 0);
test('but it is still seen by the listener', seen.includes('a'), true);
test('a repeating Enter is ignored', (() => { box.value = 'y'; const before = submitted.length; press('Enter', { repeat: true }); return submitted.length - before; })(), 0);
test('Enter while composing is ignored', (() => { box.value = 'z'; const before = submitted.length; press('Enter', { isComposing: true }); return submitted.length - before; })(), 0);
test('an empty box submits nothing', (() => { box.value = ''; const before = submitted.length; press('Enter'); return submitted.length - before; })(), 0);
test('a box of spaces submits nothing either', (() => { box.value = '   '; const before = submitted.length; press('Enter'); return submitted.length - before; })(), 0);
test('the value is trimmed', (() => { box.value = '  Kano  '; press('Enter'); return submitted.at(-1); })(), 'Kano');
test('event.key is a string, not a number', typeof press('Enter').key, 'string');
test('Escape is a key name too', press('Escape').key, 'Escape');
test('and so is the space bar, spelled as a space', press(' ').key, ' ');

event.key gives a name — 'Enter', 'Escape', 'ArrowUp', and a single space for the space bar. keyCode and which are deprecated and give numbers that vary by keyboard layout, so === 13 is code you may still meet but should not write.

The two guards are what separate a working handler from an annoying one. event.repeat is true while a key is held down, so without that check holding Enter submits repeatedly. And event.isComposing is true while text is being composed — entering Chinese, Japanese or Korean, or using a compose key for accents — where Enter means "accept this candidate", not "submit the form". Ignoring it makes the form unusable for a large share of the world, and the bug is invisible if you only ever type in English.

Common mistakes

  • Checking keyCode === 13. It is deprecated. Compare event.key with 'Enter'.
  • Not checking event.repeat. Holding Enter submits again and again.
  • Ignoring event.isComposing. Enter in the middle of composing a character submits half-written text.

Try it yourself

  1. Make Escape clear the box without submitting.
  2. Show the submitted items under the box as a numbered list, updated after each Enter.
  3. Let Shift+Enter add the text without clearing the box. (Hint: event.shiftKey is true while Shift is held.)

Keep practising

Newsletter

New writing, when it lands.

Occasional notes on shipping software with AI agents. No schedule, no filler, unsubscribe in one click.