Preventing Double Form Submission With jQuery Revisited

I had a request via IM for a more complete example of doing validation within a form submission. I threw together a quick example here to better explain my thought process. Please remember I'm new to jQuery so what I'm doing might not be an example of best practices. Feel free to suggest an alternative.

So essentially I need to capture the submit event of my form. In this case I'm assuming a single form so I simply refer to the tag name in my selector, but I'm sure you could just as easily refer to an id. Here is a simple wrapper to capture the form submission:

$(document).ready(function(){
   $('form').submit(function(){
      //do something
   });
});

So any time the form is submit I can take some action. Lets assume a super simple form on our page:

<form name="testForm">
   <div>
      <div class="label">Name</div>
      <div class="inputContainer"><input type="text" name="name" id="name" value="" /></div>
      <div class="msgContainer" id="nameMsg">I said enter a name!!</div>
      <div class="clear"></div>
   </div>
   <div>
      <div class="label">&nbsp;</div>
      <div class="inputContainer" id="submitContainer"><input type="submit" name="submit" value="submit" /></div>
      <div class="clear"></div>
   </div>
</form>

Nothing too fancy, just a text input, a validation msg container and a submit button. The first thing I want to do is hide the validation message so I don't confuse my user. I can do this by simply adding a call like so:

$(document).ready(function(){
   //hide the validation msg
   $('#nameMsg').hide();
   $('form').submit(function(){
      
   });
});

Cool. Now the validation message is hidden as soon as the DOM is ready. Now to put some logic in the submit event handler. This demo just does a simple check for length. Your business logic could be as complex as you need it to be.

$(document).ready(function(){
   //hide the validation msg    
   $('#nameMsg').hide();
   
   $('form').submit(function(){
      //validate that the username was entered       
      var n = $('#name').val();
      if(!n.length){
         $('#nameMsg').show();
      }
   
      
   });
});

We'll probably have a few fields to check in real life so lets set a variable to flag that all fields are valid. Then we'll check that variable and return out appropriately:

$(document).ready(function(){
   //hide the validation msg    
   $('#nameMsg').hide();
   
   $('form').submit(function(){
      var isValid = true;
      //validate that the username was entered       
      var n = $('#name').val();
      if(!n.length){
         isValid = false;
         $('#nameMsg').show();
      }
   
      if(isValid){
         return true;
      }
      else{
         return false;
      }
   });
});

Finally, if the form is valid then lets hide all of our validation messages and swap out the submit button for a 'Saving' message:

if(isValid){
   //hide all the validation msgs    
   $('.msgContainer').each(function(){
      $(this).hide();
   });
   
   $('#submitContainer').html('<span>Saving...</span>');
   return true;
}

Note the use of the class selector ('.msgContainer') and the call to each(). This will iterate over every element that has the class 'msgContainer' and the call to $(this).hide() will make sure they're all hidden. Then we set the html of the submit container and return out of the function.

Here is the complete example:

<html>
<head>
<script src="jquery-1.2.6.min.js" type="text/javascript"></script>
<script>
$(document).ready(function(){
   //hide the validation msg    
   $('#nameMsg').hide();
   
   $('form').submit(function(){
      var isValid = true;
      //validate that the username was entered       
      var n = $('#name').val();
      if(!n.length){
         isValid = false;
         $('#nameMsg').show();
      }
   
if(isValid){
   //hide all the validation msgs    
   $('.msgContainer').each(function(){
      $(this).hide();
   });
   
   $('#submitContainer').html('<span>Saving...</span>');
   return true;
}
      else{
         return false;
      }
   });
});
</script>
<style>
.label{
   float: left;
   width: 100px;
}
.inputContainer{
   float: left;
}
.msgContainer{
   float: left;
   color: red;
}
.clear{
   clear: both;
}
</style>
</head>
<body>
<h1>Enter your name!</h1>
<form name="testForm">
   <div>
      <div class="label">Name</div>
      <div class="inputContainer"><input type="text" name="name" id="name" value="" /></div>
      <div class="msgContainer" id="nameMsg">I said enter a name!!</div>
      <div class="clear"></div>
   </div>
   <div>
      <div class="label">&nbsp;</div>
      <div class="inputContainer" id="submitContainer"><input type="submit" name="submit" value="submit" /></div>
      <div class="clear"></div>
   </div>
</form>
</body>
</html>

Comments
If you'd feel more comfortable simply disabling the submit button instead of swapping it out you could always call:

$('#submitButton').attr("disabled", "true");

Assuming you had an id of submitButton on your submit button :)

Or see Tony's suggestion in this comment:

http://cfsilence.com/blog/client/index.cfm/2008/7/...
# Posted By todd sharp | 7/17/08 4:52 PM
Awesome job. :) I love jQuery.
# Posted By Todd Rafferty | 7/17/08 6:40 PM
Excellent work.

I'm going to adapt this to disable all button tags in every form on the page on submit and run it globally in an admin I'm writing to prevent double submissions.
# Posted By Adam Tuttle | 7/18/08 9:24 AM
If you're using ColdFusion, you could also use the validate="submitonce" attribute if using CFForm. I.e. <cfinput type="submit" name="btnSubmit" label="Submit" value="Submit" validate="submitonce" />.
# Posted By Steve Withington | 7/24/08 1:22 PM

Calendar

Sun Mon Tue Wed Thu Fri Sat
     12
3 4 5 6 7 8 9
10 11 12 13 14 15 16
17 18 19 20 21 22 23
24 25 26 27 28 29 30
31       

Subscribe

Enter your email address to subscribe to this blog.

Tags

actionscript ajax blogging cfsnippets coldfusion flash forms flex funny stuff misc model-glue off topic personal project learn slidesix sql

Recent Comments

Adding Auto Generated Code Downloads to BlogCFC
ada5fsa said: http://www.mountwashingto... http://extjs.com/forum/me... h... [More]

BlogCFC Survey #2
ada5fsa said: http://www.mountwashingto... http://extjs.com/forum/me... h... [More]

Most Difficult Captcha Of All Time
kokkooo said: [url=http://synchrophase.info/...]消費者金融 ブラック[/url] [url=http://geji-geji.com/]消費者金融ブラック[/url] [url=http... [More]

Most Difficult Captcha Of All Time
kokkooo said: <a href="http://synchrophase.info/...">消費者金融 ブラック</a> <a href="http://gej... [More]

Using A PlayStation 2 HDD In Your PC
Vodin said: Well dang. Thanks man, my uncle who owns a Video Game shop had a PS2 harddrive in the junk box, I sn... [More]

RSS


coldfusionbloggers

FullAsAGoog MXNA

Consumed By Feed-Squirrel.com