Main Page

Submit only once

You can actually mimic the behavior of a Submit button by creating a generic button and assigning its
onclick
event handler to submit the form:
<input type=”button” value=”Submit Form” onclick=”document.forms[0].submit()” />
Before the form is submitted, but after a Submit button is clicked, the
submit
event is fired and the
onsubmit
event handler is executed. Using the
onsubmit
event handler, it is possible to stop form sub-
mission, which is especially useful if client-side validation is necessary before the form can be submitted.
Using the event methods mentioned earlier in the book, you can cancel the event and prevent the form
submission:
function handleSubmit() {
var oEvent = EventUtil.getEvent();
oEvent.preventDefault();
}
This method can then be called from a form’s
onsubmit
event handler:
<form method=”post” action=”javascript:alert(‘Submitted’)”
onsubmit=”handleSubmit()”>
When you try to submit a form using the Submit button or the Image button, the form is not submitted.
Submit only once
A constant problem in Web forms is that users get very impatient when submitting a form. If the form
doesn’t disappear right away when they click the Submit button, users often click multiple times. The
problems this causes vary from creating duplicate requests to charging a credit card more than once. The
solution is a very simple one: After the user clicks the Submit button, you disable it. Here’s how: Use a
regular button, not a Submit button, and disable the button after the user clicks it. So instead of using
this code:
<input type=”submit” value=”Submit” />
use this code:
<input type=”button” value=”Submit”
onclick=”this.disabled=true; this.form.submit()” />
When this button is clicked, it is disabled by setting the
disabled
property to
true
. Then, the form is
submitted (note that the code uses the
this
keyword to reference the button and the
form
property to
reference the form that it’s a part of). This code can also be encapsulated in a function, if you so desire.
The
onsubmit
event handler enables you to validate a form before submission, but
only if you use one of the two types of buttons mentioned previously. When using
the
submit()
method, the
submit
event isn’t fired, so all validation should be done
prior to making the call.
341
Forms and Data Integrity
14_579088 ch11.qxd 3/28/05 11:40 AM Page 341


JavaScript EditorFree JavaScript Editor     Ajax Editor


©