Detecting the enter key with javascript

Posted: 08/02/2008

In this how-to we will inspect a key-press triggered event instance to determine if the enter key was pressed. The event instance has a property called keyCode, which indicates the enter key when set to 13. Let’s start with a text input:

  <input type="text" id="foo">

We can write an event handler to alert the contents of this field when enter is pressed:

  document.getElementById('foo').onkeypress = function(e){
    if (!e) e = window.event;   // resolve event instance
    if (e.keyCode == '13'){
      alert(this.value);
      return false;
    }
  }

IE will append the event instance to the window instead of passing it as a parameter to the handler, so the first line of our handler ensures that e is set to the event instance, regardless of browser. Next we see if keyCode is equal to ‘13’, which indicates the enter key. If enter was pressed we alert the contents of the text box and return false. We return false in case our input is within a form and we want to prevent the event’s default behavior (i.e. submitting the form).

Let’s try it out, type something in the field below and hit enter:

I would also like to mention that there is no need to resolve the event instance if we use jquery or prototype. Here is how we would accomplish the same thing with jquery:

  $('#foo').keypress(function(e){
    if (e.keyCode == '13'){
      alert(this.value);
      return false;
    }
  });

And finally, with prototype:

  $('foo').observe('keypress', function(e){
    if (e.keyCode == '13'){
      alert(this.value);
      Event.stop(e);
    }
  });

About Me

I'm a skier, web developer, entrepreneur, freelancer, and all around stand-up guy living in Manhattan. This is me, repping one of my favorite shirts...

Follow me on twitter or send me an email.

All Posts

Music Blogs