Press Enter to Submit
Javascript February 07, 2008

This is just a quick entry to mention that forms should always be allowed to be submitted using the Enter key.

Sometimes when you want the form to do something special (i.e. some special Javascript/AJAX function), users will have to click the button because using Enter will still submit the form. The way around this is to write:


<form onSubmit="return false;">
...
<input type="submit" value="Submit" onclick="doSomething();
return false;">


There are two parts to this:
(a) the form tag cannot have a method or action attribute. In fact, you should have the onSubmit attribute simply return false.

(b) writing "return false" at the end of the onclick prevents the form from being formally submitted (a la page reload) after calling your Javascript function.

It's much more satisfying to be able to press Enter at the end of a form than to have to move the mouse and click the button.

Additionally, consider doing the following when submitting a form via AJAX:

1) Change the value of the submit button to "Submitting"
2) Disable the form fields (including the submit button)
3) Display an ajax-loader icon (A cool generator can be found here)
4) When everything's been processed, then change the value back and re-enable the form (after resetting it)

This structure has been proven to be very user-friendly, as it gives the user immediate feedback upon submit of what is going on and when it's finished.


Other Javascript Posts

Mar 15, 2008

An AJAX Restaurant

I was putting together a little presentation talking about what AJAX is and why it's useful and I was trying to think of some kind of real-world analogy to explain the benefits. I came up with the interactions you have a...

Jul 27, 2007

Improving User Experience Through Client-Side Scripting

I feel pretty comfortable with AJAX and Javascript nowadays, which is great because I just started playing around intensely with these two languages in late April. Being that I'm interested in user-interface design an...

Jun 26, 2007

AJAX solutions

For a neat collection of AJAX articles, visit Smashing Magazine. So yeah, I've gotten really comfortable with using Javascript and AJAX everywhere. It really makes things both easier and cooler, mostly because all upd...