View Full Version : input button responding to enter

10-25-2006, 05:29 PM
I have forms that I submit with AJAX so I don't use the usual

<input type="submit" />

Instead I use

<input type="button" onClick="someFunctionThatPostsData( )" />

This unfortunately means I lose the ability to submit a form with the enter key which is something that I've found a lot of my users take for granted. Thus throwing them off a bit when nothing happens. Anyone know of a work-around?

10-26-2006, 04:48 AM
This is an interesting problem. The only thing that I can think of off the top of my head is to create a form as normal then for the onSubmit event of the form call the ajax function and return false so that the form is not actually submitted.

For example:

<form onSubmit="{someFunctionThatPostsData( ); return false;}"> form fields </form>

This way you should be able to use a submit button insead of a plain jscript button meaning that the user will be able to press enter to submit the form like they are used to.

Let me know how you get on :)

11-13-2006, 05:47 PM
Ah that totally worked! And it's such a simple solution. Thanks much.

11-14-2006, 12:40 AM
That's a good solution except if javascript is turned off then the form WOULD get submitted as a normal form, which may be a big NO NO for you (or could be a big PLUS?).

So if you'd rather the form didn't work at all without js rather than work in the normal fashion, something like this could do it...

.. also the programming model is clearer as everything is kept as javascript:

function DocumentKeyDown(event)
// Get event keycode & element that fired the event
var e = event || window.event;
var eleSrc = e.srcElement || e.target;
var intKey = e.keyCode || e.which;

// If element was a TEXTAREA then just return
if (eleSrc.tagName.toUpperCase() == "TEXTAREA")

// If they press return then sumit the form
if (intKey == 13)

function sendForm()
// Send AJAX form stuff here

document.body.onkeydown = DocumentKeyDown;

11-14-2006, 05:41 AM
My form is in a div that is displayed with javascript so users wouldn't even be able to see the form at all without it.

I'll definitely keep this in mind though if I'm ever in a situation where I need to listen for key events.