FlyingCat FlyingCat - 1 month ago 5x
Javascript Question

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

I only have 1 input field and I want to register onChange and onKeyPress event to detect when the users finish their input or press the Enter key. I need to use javascript only. Thanks for the help.

I have:

var load = function (){
//I want to trigger this function when user hit Enter key.

document.getElementById('co').onchange=load; //works great
//not sure how to detect when user press Enter


//no form just a single input field
<input type='text' id='co'>

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