Posted by & filed under Javascript/YUI/jQuery.

Using Prototype we can capture the return key (and other key presses) to replace the usual form submission with our own Javascript functions. This is useful if we, say, want to do some Javascript-based error checking on the form prior to submission when the user presses their return key, or invoke a search via a return key press within a search field.

Using Prototype we can capture the return key (and other key presses) to replace the usual form submission with our own Javascript functions. This is useful if we, say, want to do some Javascript-based error checking on the form prior to submission when the user presses their return key, or invoke a search via a return key press within a search field.

To do this:

$('css_ID').observe('keypress', function(e) {
	var key = e.which || e.keyCode;
	if (key == Event.KEY_RETURN) {
		yourFunction();
	}
});

$('yourformID').observe('submit', function(e) {
	e.stop();
});

Just replace “css_ID” with the CSS ID of the form element you want to use to capture key presses (e.g. a search field), replace “yourformID” with the ID assigned to your form, and replace “yourFunction” with whatever Javascript function you’d like to use to act on this key press. A quick Google search will show you some of the other key presses you can use in addition to KEY_RETURN.