Go Back   CodingForums.com > :: Client side development > JavaScript programming

Before you post, read our: Rules & Posting Guidelines

Reply
 
Thread Tools Rate Thread
Enjoy an ad free experience by logging in. Not a member yet? Register.
Old 10-22-2012, 06:35 PM   PM User | #1
Rain Lover
Regular Coder

 
Join Date: Nov 2009
Posts: 138
Thanks: 9
Thanked 0 Times in 0 Posts
Rain Lover is an unknown quantity at this point
Validate optional form fields with default values

Sample form:

Code:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title></title>
  <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js"></script>
  <script type="text/javascript" src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.9/jquery.validate.min.js"></script>
  <script type="text/javascript">
  $(document).ready(function(){
$("#cname, #cemail, #curl, #ccomment").focus(function(){
  if( this.value == this.defaultValue ) {
    $(this).val("");
  }
}).blur(function() {
  if( !this.value.length ) {
    $(this).val(this.defaultValue);
  }
});
$.validator.addMethod("noName", function(value, element) {
return value != element.defaultValue;
}, "Please enter your name.");
$.validator.addMethod("noComment", function(value, element) {
return value != element.defaultValue;
}, "Please enter your comment.");
$("#commentForm").validate();
  }); 
  </script>
</head>
<body>
  <form id="commentForm" action="">
   <p>
     <input id="cname" name="name" size="25" class="required noName" value="Name">
   </p>
   <p>
     <input id="cemail" name="email" size="25" class="email" value="Email">
   </p>
   <p>
     <input id="curl" name="url" size="25" class="url" value="URL">
   </p>
   <p>
     <textarea id="ccomment" name="comment" rows="5" cols="35" class="required noComment">Comment</textarea>
   </p>
   <p>
     <input class="submit" type="submit" value="Submit">
   </p>
 </form>
</body>
</html>
If you click the submit button, you get error messages on Email and URL fields while they are optional. How can I prevent it?
Rain Lover is offline   Reply With Quote
Reply

Bookmarks

Tags
forms, jquery, validation

Jump To Top of Thread


Thread Tools
Rate This Thread
Rate This Thread:

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off

Forum Jump


All times are GMT +1. The time now is 04:16 PM.


Advertisement
Log in to turn off these ads.