How-To: Capture ‘return key’ from a field with Protoype.js
Prototype provides an excellent abstraction mechanism for event handling in javascript. I needed to capture when a user hit the ‘return key’ inside a text box, and then perform a specified action. Using the observe function and the KEY_RETURN constant, you can easily detect when this is done.
Simply place the following code in a function that is called after your myInputField equivalent has been added to the DOM:
$('myInputField').observe('keypress', function(event){
if(event.keyCode == Event.KEY_RETURN) {
// do something useful
alert('Enter key was hit!');
// stop processing the event
Event.stop(event);
}
});
More information is available from the prototype.js site. A really good tutorial on the same topic is available here. Thanks for the comments guys – I’ve fixed the typo’s!

Leave a Reply