logo

When Pressing Enter Submits Forms

Still on forms, here's something I thought I understood but still managed to learn more about yesterday.

If you have a simple form with, say, a couple of text fields and a button on it, pressing enter in either of these fields will submit the form. We've probably all seen this and take it for granted.

Well, yesterday I learnt something new and came up with a workaround I thought worthy of your attention.

Imagine a form like yesterday's, where, at the bottom, we have two type="submit" buttons, like so:

Personal Details
First NameLast Name
CountrySex Male
Female
Age

My first surprise was the enter-to-submit worked at all on such a large form (type a value in a field above and press enter). While I knew enter didn't submit forms with TEXTAREAs on it I thought it also didn't work for forms of any significant length. However, the actual form I was working with was made up of about twenty fields of various types, but not a TEXTAREA.

Not only was it odd that pressing enter submitted the form, but the form was going backwards and not on to the next tab/page.

The reason for this is simple. When you press enter the browser (well, IE and Firefox at least) mimics a click of the first submit button on the form. In my case this button was the "back" button (notice it's highlighted in the above form) and so the form behaved all weird.

Here's my simple fix — put the buttons in reverse order in the HTML and use CSS to reverse their order back again. Notice in the form below that the second button is highlighted and defaulted (focus cursor in a field first).

Personal Details
First NameLast Name
CountrySex Male
Female
Age

 

In this form the buttons are inside a P tag, which has a class of "reversed". In the CSS we add:

p.reversed input{
float:right;
}

As simple as that!

Further reading:

Comments

  1. Cool! I don't find myself with this problem often, but that is a clever trick to remember.

Your Comments

Name:
E-mail:
(optional)
Website:
(optional)
Comment:


About This Page

Written by Jake Howlett on Fri 7 Jul 2006

Share This Page

# ( ) '

Comments

The most recent comments added:

Skip to the comments or add your own.

You can subscribe to an individual RSS feed of comments on this entry.

Let's Get Social


About This Website

CodeStore is all about web development. Concentrating on Lotus Domino, ASP.NET, Flex, SharePoint and all things internet.

Your host is Jake Howlett who runs his own web development company called Rockall Design and is always on the lookout for new and interesting work to do.

You can find me on Twitter and on Linked In.

Read more about this site »

More Content