article

Sunday, April 29, 2012

Contact form with jquery

html form
<div id="contactform">
        <form id="contact" action="#">
       <fieldset>
         <label for="name" id="name_label">Name <br /></label>
         <input type="text" name="name" id="name"  value="" class="text-input" />
         <label for="email" id="email_label">E-mail<br /></label>
         <input type="text" name="email" id="email"  value="" class="text-input" />
         <label for="msg" id="msg_label">Message</label>
        <textarea cols="60" rows="10" name="msg" id="msg" ></textarea> <br class="clear" />
         <input type="submit" name="submit" class="button" id="submit_btn" value="Submit"/>
       </fieldset>
        </form>
         <br class="clear" />
        <span class="error" id="name_error">Please enter name !</span>
        <span class="error" id="email_error">Please enter email address !</span>
        <span class="error" id="email_error2">Please enter valid email address !</span>
        <span class="error" id="msg_error">Please enter message !</span>
     </div>
jQuery(function() {
  jQuery('.error').hide();
  jQuery(".button").click(function() {
  // validate and process form
  // first hide any error messages
    jQuery('.error').hide();
  
   var name = jQuery("input#name").val();
  if (name == "") {
      jQuery("span#name_error").show();
      jQuery("input#name").focus();
      return false;
    }
   var email = jQuery("input#email").val();
   if (email == "") {
      jQuery("span#email_error").show();
      jQuery("input#email").focus();
      return false;
    }
 
 var emailReg = /^([\w-\.]+@([\w-]+\.)+[\w-]{2,4})?$/;
 if(!emailReg.test(email)) {
 jQuery("span#email_error2").show();
    jQuery("input#email").focus();
      return false;
 }
 
   var msg = jQuery("textarea#msg").val();
   if (msg == "") {
   jQuery("span#msg_error").show();
   jQuery("textarea#msg").focus();
   return false;
    }
  
  var dataString = 'name='+ name + '&email=' + email + '&msg=' + msg;
  //alert (dataString);return false;
  
   jQuery.ajax({
      type: "POST",
      url: "process.php",
      data: dataString,
      success: function() {
        jQuery('#contactform').html("
"); jQuery('#message').html("Contact Form Submitted!") .append("We will be in touch soon.
") .hide() .fadeIn(1500, function() { jQuery('#message'); }); } }); return false; }); });

Related Post