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:
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).
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:
Cool! I don't find myself with this problem often, but that is a clever trick to remember.