JavaScript Keypress Event – the right way

I had an occassion where I had to capture the “enter” key press in a text box and couldn’t quite remember how to do that. So, like the well-adjusted web developer I am, I Google’d for the answer. I was suprised to find how many different solutions there were and how some of them just plain didn’t work.

I turned to the tried-and-true Prototype library (because that’s how I remembered doing it in the first place). The bonus with using Prototype is that it will actually be browser compatible.

Here is the penultimate solution to capturing an “enter” keypress in an HTML input text box.

The HTML:

<input type="text" name="my_text" id="my_text" value="" />

The JavaScript:

<script type="text/javascript"><!--
function onMyTextKeypress(event)
{
if (Event.KEY_RETURN == event.keyCode) {
// do something usefull
alert('Enter key was pressed.');
}
return;
}

Event.observe('my_text', 'keypress', onMyTextKeypress);
//-->
</script>

Now, don’t forget to include the prototype.js script in the HTML page!

<script type="text/javascript" src="/js/prototype.js"></script>

The JavaScript must execute after the DOM elements are rendered. One way to do it is to put the JavaScript code in a SCRIPT element after the INPUT element. However, another way would be to put the following code in the SCRIPT element in the HEAD element:

Event.observe(window, 'load', function() {
Event.observe(Event.observe('my_text', 'keypress', onMyTextKeypress);
});

I like this method because all the JavaScript can be kept in the HEAD, or in a JS library file, instead of splattering the code throughout the document body.

References:

Prototype Event.observe API