A Study in Flash Form Submission

In HTML, fill-in forms are a breeze to create: take one
<form> tag; add user-input tags to taste; bake at 350 degrees for one hour; serve and enjoy.

Historically, the creating forms in Flash hasn't been so simple. With
the release of Flash MX's Flash UI
components, things got a lot easier, but form submission is still
trickier in Flash than it is in HTML. In HTML, forms can be submitted via
a submit button or "automagically" via the Enter key. Flash does not have
built-in support for Enter-key form submission, so we must handle the
Enter key manually. The remainder of this article explains how to do just
that. Download the source code for the following discussion here.

Flash forms are typically a collection of user interface components. To
"submit" a form to a server-side script or application, we must manually
assemble the value of each component into either a LoadVars or an XML
object, and then invoke that object's sendAndLoad() or
send() method.

These steps are usually handled by a custom function or
method. Consider, for example, a simple login form with a user name text
field, a password text field, and a submit button. The text fields are
single-line input text fields with instance names of username_txt and
password_txt. The submit button is an FPushButton instance
named submit_pb. To handle form submission, we define a custom
submitForm() function. The code on our form's timeline looks
like this:

To make our submit button (submit_pb) invoke
submitForm() when pressed, we use the
FPushButton component's setClickHandler() method
as follows:

// This code must be on a frame in the same
// timeline as the earlier submitForm() function definition.
submit_pb.setClickHandler("submitForm");

Now for the tricky part: when the Enter key is pressed, we want to
invoke submitForm(), but only if one of the text fields in
the form is focused. To handle the Enter key, we'll add new custom methods
to the TextField class. First, let's rough out a new method
to check for Enter keystrokes. We'll call the method
onKeyDown() so that any TextField instance can
register to receive keystroke event notifications from the built-in Key
object.

Our new method has a problem: if the user holds down the Enter key,
we'll get multiple keystroke events. We're only interested in the first
keystroke, so let's modify onKeyDown() to discard all but the
first press of the Enter key. We'll add a property,
pressedOnce, to track the first Enter key press, and we'll
add a new method, onKeyUp(), to clear the
pressedOnce property when the Enter key is released.