Enter key fires click event on form submit button

I ran into an odd situation today where pressing the enter key in a form would submit the form as if I’d clicked the submit button. I captured the event and inspected the “which” and keyCode and they both said “1”, which is the left click of a mouse (13 is the enter key). Apparently pressing the enter key also fires the click event of the submit button in a form! This is something browsers are starting to implement now as the html5 spec says the following:

“User agents may establish a button in each form as being the form’s default button. This should be the first submit button in tree order whose form owner is that form element, but user agents may pick another button if another would be more appropriate for the platform. If the platform supports letting the user submit a form implicitly (for example, on some platforms hitting the “enter” key while a text field is focused implicitly submits the form), then doing so must cause the form’s default button’s activation behavior, if any, to be run.”

I need to separate the enter key from the click action of the submit button, so the code below will do the trick.

$('form').bind("click keypress", function(e) {
	var keyCode = e.which || e.keyCode;
	if (keyCode == 13) {
		//alert("ENTER pressed");
		 * prevent the next automagic action that occurs... a click 
		 * action on the form's submit button.
	} else {
		var sender = e.target;
		if (sender.type == "submit") {
			//alert("Submit button " + sender.id + " clicked");
		} else {
			//some other keypress
	return true;

Leave a comment

Your email address will not be published. Required fields are marked *