Disabling the Submit Button to Prevent Double Form Submission
Posted in Javascript / jQuery, Web Development on December 21st, 2010 by Steve Marks – Be the first to commentWhether it be due to a users lack of tech know-how or a twitch of the finger, a secondary click of a forms ‘Submit’ button could result in the form being submitted twice. Depending on the action of the form this could in turn send two enquiries, create two orders or insert a record into the database twice.
To get around this we can use a very simple bit of Javascript to disable the ‘Submit’ button after the first click. Even if the user does end up clicking twice or more these additional clicks will not count.
A Demonstration
Below is a standard button. Go ahead, click it multiple times and you will see each click is received:
Now for our updated button that only allows one click by the user:
Ok, now that we’ve seen it in action lets look at how to implement this using Javascript.
The Code
Depending on how your form already works we can go about adding this feature one of two ways:
1) No form validation exists / Adding the code directly onto the button
If your form doesn’t contain any validation we can add the code directly to the button. The example button shown above uses the following code:
<input type="submit" name="Submit" value="Submit" onclick="this.disabled=true; this.value='Please Wait...';" />
2) Form validation already exists / Adding the code to a pre-existing function
If Javascript validation already exists on your form to check the users input it’s easier to update this function with your new code. I’ve included below an example of how this might look:
<script type="text/javascript">
function validateForm(formObj) {
if (formObj.username.value=='') {
alert('Please enter a username');
return false;
}
formObj.submitButton.disabled = true;
formObj.submitButton.value = 'Please Wait...';
return true;
}
</script>
<form name="frmTest" action="" method="post" onsubmit="return validateForm(this);">
Username: <input type="text" name="username" value="" /><br />
<input type="submit" name="submitButton" value="Submit" />
</form>
If adding the disabling functionality to your button using the second method ensure that you place the new code after the validation takes place. If you place it before any of the checks your user will not be able to submit the form again should it fail validation.
Today we used the input tags ‘disabled’ attribute. You can view more information about this by following the link: www.w3schools.com/TAGS/att_input_disabled.asp





Hi, I'm Steve Marks, the voice (or at least the typist) behind this blog. I'm 24 and currently live in the UK.