How to detect when the user presses Enter in an input field

document.getElementById('foo').onkeypress = function(e){
    if (!e) e = window.event;
    var keyCode = e.code || e.key;
    if (keyCode == 'Enter'){
      // Enter pressed
      return false;
    }
  }

DEMO


None of these answers as of yet specifically answer this question. The question is in 2 parts. 1. Enter is Pressed. 2. The uses is focused on an input.

Jquery

$('#input-id').on("keyup", function(e) {
    if (e.keyCode == 13) {
        console.log('Enter');
    }
});

Vanilla JavaScript

inputId = document.getElementById('input-id');
inputId.addEventListener('keyup', function onEvent(e) {
    if (e.keyCode === 13) {
        console.log('Enter')
    }
});

This way ENTER is only detected when the user presses enter FROM that input.


More recent and much cleaner: use event.key instead of event.keyCode. No more arbitrary number codes!

const node = document.getElementById('co');
node.addEventListener('keydown', function onEvent(event) {
    if (event.key === "Enter") {
        return false;
    }
});

Mozilla Docs

Supported Browsers