Friday, 25 May 2012

JavaScript: avoid double submit in forms

   


When working with complex forms, a developer's nightmare is the double submit of data. There are many users that double click on links, buttons etc, as if the browser was just like their desktop. If a user submit the form data twice, it could be that we will gather information twice, creating redundant records in our database.
There's a simple solution to that, and today I will show you how to do it with a little JavaScript function.
Follow me...

The form
First of all let's create a form. In the example we will have just a simple input box and a submit button:
<form name="form1">
<input type="text" name="varText">
<input type="button" name="btn" value="Submit" onClick="btnSubmit()">
</form>
As said, we have an input box and a button. On a user click, the btnSubmit() function is triggered.

The function
The JavaScript function will just change the button value, it will disable the button and finally it will submit the data:
<script>
function btnSubmit()
{
  document.form1.btn.value = "Submitting...";
  document.form1.btn.disabled = true;
  document.form1.method = "post";
  document.form1.action = "submit.asp";
  document.form1.submit();
}
</script>
As said, the first two lines of the function are just changing the button value and disabling the button itself.
After that, we just submit the gathered data to another page (submit.asp) which will actually submit the information in the preferred way (to a database, to an email module or whatever).

Simple and straightforward.

0 thoughts:

Post a Comment

Comments are moderated. I apologize if I don't publish comments immediately.

However, I do answer to all the comments.