Learning jQuery, Day 8 : Preventing Form Double-Processing
Today is a quick tutorial on how to prevent the problem of a user clicking the "submit" button more than once -- usually in the case of a slow-responding form processing page.
Here is the form:
<form id="form_processor" action="doForm.cfm" method="post">
<label for="username">User name: </label><input type="text" id="username" name="username" /><br />
<label for="password">Password: </label><input type="password" id="password" name="password" /><br />
<span id="submit"><input type="submit" value="OK" /></span>
</form>
<cfinclude template="form.pgm">
<label for="username">User name: </label><input type="text" id="username" name="username" /><br />
<label for="password">Password: </label><input type="password" id="password" name="password" /><br />
<span id="submit"><input type="submit" value="OK" /></span>
</form>
<cfinclude template="form.pgm">
I've included "form.pgm", where my JavaScript looks like this:
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
<script>
$('#form_processor').submit(function(){
$('#submit').html('<img src="25.gif" border="0"> Processing');
});
</script>
<script>
$('#form_processor').submit(function(){
$('#submit').html('<img src="25.gif" border="0"> Processing');
});
</script>
When the user clicks the submit button, the form processing will be intercepted by this code. I then use jQuery to replace the form button with a spinning button and the word "Processing".
You can see it running http://dev.citymind.com:8500/test/blog_jquery/day8/form.cfm
For the form processing page, I simulated a slow page with this code:
<cfset thread = CreateObject('java', 'java.lang.Thread')>
<cfset thread.sleep(4000)>
<cfoutput>
<p>Your form has been processed.</p>
<p>Your username is #form.username# and your password is #form.password#</p>
</cfoutput>
<cfset thread.sleep(4000)>
<cfoutput>
<p>Your form has been processed.</p>
<p>Your username is #form.username# and your password is #form.password#</p>
</cfoutput>


$('#submit').attr('disabled', 'disabled');
Even with the text change, they could still click it. Or better yet, you could use the .blockUI() plugin to gray out the form (or the div containing the form) afterwards.
<cfinput type="submit" value="ok" name="ok" validate="SubmitOnce" />