HTML: How to Disable the Submit Button After Submit

Solution

<script type="text/javascript">
	function disableFormElements(form){
		setTimeout(function(){
			for (var i=0; i<form.elements.length; i++) 
			    form.elements[i].disabled = true;
		}, 1);
	}	
 
<form name="formName" action="page.xsp?p1=1&p2=2" method="post" 
onsubmit="if (!ClientValidation()) return false; disableFormElements(this)">

Explanation

Disabling the submit button after it has been clicked is a very common need that still has no built-in DOM solution. A typical scenario for using such functionality is preventing double submission while creating a new record based on the form data. Or you may have a page with criteria inputs and several buttons to obtain different reports and/or display filtered data, and the server needs to know the name of the clicked button. Disabling the submit button right on its “click” event will not pass the button name to server, which usually has forked logic depended on the form variables. You may find many “jazzy” solutions in the Internet; my one features the following:

• Simple and reusable
• Applied for all the submit buttons on a form and prevents editing the inputs
• Gives the user a clear indication that a form submission has been started
• A good place for starting an application-wide progress gauge
• No jQuery or another JavaScript extensions required

Warning: while the server response time is unpredictable and may take dozens of seconds, the client validation processing is usually instant. Still, a compound validation (ClientValidation() in my snippet of code), especially with asynchronous calls should be taken into account; in this case, just disable the form before client validation and re-enable it after the validation is over.

Happy coding!

Comments

Thank you.

I was stuck with disabling the submit button since a few days. Finally found a solution. Thank you.