Forms on websites are a handy way to get information from your visitors. However it’s easy for a visitor to accidentally send more than one copy of a form by clicking on the form’s “submit” button more than once. The end result can be that identical emails get sent to the Webmaster, or identical records get added to a database.
How does it work?
<head></head> area of your Web page:
The script initially sets a variable,
false when the page first loads. Then, when the
submit_form() function is called (see below), it sets
true and submits the form by returning
true. However, if the form has already been submitted once,
form_submitted will already be
true. In this case, the function displays a warning, and returns
false to stop the form being submitted again.
<form onsubmit="return submit_form()"> <p>Your Name:<br /> <input type="text" name="visitor_name" /></p> <p>Your Email Address:<br /> <input type="text" name="visitor_email" /></p> <p><input type="submit" name="submit" value="Submit Form" /></p> </form>
You’ll notice the
onsubmit="return submit_form()" attribute inside the
<form> tag. This sets our
onSubmit event for the form. This is the event that is triggered when the visitor tries to submit the form. If our function returns
true, the form will be submitted. If it returns
false, the form will not be submitted.
Allowing Changes to the Form
There’s one small problem with our script. It would be nice if we could let the visitor change one or more fields in the form and re-submit the form. This could be useful if, for example, they want to submit two different entries, or if there was a validation error that they need to correct. Currently, the only way to re-submit the form in this situation is to reload the page first, which isn’t very intuitive.
By resetting the
form_submitted variable back to
false whenever a field is changed, we can allow the visitor to re-submit the form provided they have changed at least one of the fields since they last submitted. We can do this by adding an
onChange attribute to each form field’s tag – for example:
<p>Your Name:<br /> <input type="text" name="visitor_name" onchange="form_submitted=false" /></p> <p>Your Email Address:<br /> <input type="text" name="visitor_email" onchange="form_submitted=false" /></p>