@owenshifflett Forget @veryblair, she left me too!

WordPress & jQuery Contact Form without a Plugin

There are lots of WordPress plugins for contact forms, but wouldn’t it be nice to have more control over the markup? In this tutorial, I am going to show how to use a custom page template to create a contact form in WordPress without a plugin.

Some people may want to skip the post and get to the demo and source files:

View Demo Download Source Files

So, why not use a plugin?

Well, I think that a contact form is so simple that a WordPress plugin that doesn’t provide exactly what I want is pretty lame. Plus, I don’t need all those fancy interfaces for building the form; I just need the code.

The Plan

Our plan is to create a custom WordPress Page Template, then create a page that uses that template. Finally, we will add in a little jQuery to improve the form. Let’s write a little pseudo code to help determine how our page template will be structured.

Pseudo Code

If form was submitted validate it
	If the form was submitted successfully
		Send email(s)
	Else
		Set variables to show errors

If the form was submitted successfully
	Show thank you message
Else
	Show form (with errors if there are any)

Creating the WordPress Page Template

Alright, so first, we are going to start with some basic stuff: define the template name, include the header/sidebar/footer, and setup the basic structure of our pseudo code.

<?php
/*
Template Name: Contact Form
*/
?>

<?php
//If the form is submitted
if(isset($_POST['submitted'])) {
	//If there is no error, send the email
	if(!isset($hasError)) {

	}
} ?>

<?php get_header(); ?>

<?php
//If the email was sent, show a thank you message
//Otherwise show form
if(isset($emailSent) && $emailSent == true) {
?>

<?php } else { ?>

<?php } ?>

<?php get_sidebar(); ?>

<?php get_footer(); ?>

The Form

Next, let’s code the actual form. I also want to provide the ability for the user to enter some text to go above the form, so we are going to use the regular loop:

<?php if(isset($emailSent) && $emailSent == true) { ?>

	<div class="thanks">
		<h1>Thanks, <?=$name;?></h1>
		<p>Your email was successfully sent. I will be in touch soon.</p>
	</div>

<?php } else { ?>

	<?php if (have_posts()) : ?>

		<?php while (have_posts()) : the_post(); ?>
			<h1><?php the_title(); ?></h1>
			<?php the_content(); ?>

			<?php if(isset($hasError) || isset($captchaError)) { ?>
				<p class="error">
					There was an error submitting the form.
				<p>
			<?php } ?>

			<form action="<?php the_permalink(); ?>" id="contactForm" method="post">

			</form>

		<?php endwhile; ?>
	<?php endif; ?>
< } ?>

If the emailSent variable is set to true, we display the thank you message. Otherwise, we show the form. So we are outputting the title of the page, and any content that was entered. Then, we are checking to see if there was an error. Finally, we display the form:

<ol class="forms">
	<li>
		<label for="contactName">Name</label>
		<input type="text" name="contactName" id="contactName" value="
		<?php if(isset($_POST['contactName'])) echo $_POST['contactName'];?>"
		 class="requiredField" />
		<?php if($nameError != '') { ?>
			<span class="error"><?=$nameError;?></span>
		<?php } ?>
	</li>

	<li>
		<label for="email">Email</label>
		<input type="text" name="email" id="email" value="
		<?php if(isset($_POST['email']))  echo $_POST['email'];?>"
		class="requiredField email" />
		<?php if($emailError != '') { ?>
			<span class="error"><?=$emailError;?></span>
		<?php } ?>
	</li>

	<li class="textarea">
		<label for="commentsText">Comments</label>
		<textarea name="comments" id="commentsText" rows="20" cols="30" class="requiredField">
		<?php if(isset($_POST['comments'])) {
			if(function_exists('stripslashes')) {
				echo stripslashes($_POST['comments']);
			} else {
				echo $_POST['comments'];
			}
		 } ?></textarea>
		<?php if($commentError != '') { ?>
			<span class="error"><?=$commentError;?></span>
		<?php } ?>
	</li>
	<li class="inline">
		<input type="checkbox" name="sendCopy" id="sendCopy" value="true"
		<?php if(isset($_POST['sendCopy']) && $_POST['sendCopy'] == true)
			echo ' checked="checked"'; ?>
		/>
		<label for="sendCopy">Send a copy of this email to yourself</label>
	</li>
	<li class="screenReader">
		<label for="checking" class="screenReader">If you want to submit this form, do not enter anything in this field</label>
		<input type="text" name="checking" id="checking" class="screenReader" value="
		<?php if(isset($_POST['checking']))  echo $_POST['checking'];?>"
		/>
	</li>
	<li class="buttons">
		<input type="hidden" name="submitted" id="submitted" value="true" />
		<button type="submit">Email me »</button>
	</li>
</ol>

Note: Line wrapping added for readability.

Ok, wow, that may seem like a lot. So let’s break down the name field to see what this code is actually doing:

<li><label for="contactName">Name</label>
	<input type="text" name="contactName" id="contactName" value="<?php if(isset($_POST['contactName'])) echo $_POST['contactName'];?>" class="requiredField" />
	<?php if($nameError != '') { ?>
		<span class="error"><?=$nameError;?></span>
	<?php } ?>
</li>

We are displaying each form field in a list item, displaying the label, input field, and then showing an error message if there is one. We are also displaying the value in the form field if it was already submitted.

So in essence, we are just doing that for each field of the form. You could easily go into the code to add more fields.

We are also using honeypot captcha to see if a bot was trying to submit the form:

<li class="screenReader">
	<label for="checking" class="screenReader">If you want to submit this form, do not enter anything in this field</label>
	<input type="text" name="checking" id="checking" class="screenReader" value="<?php if(isset($_POST['checking']))  echo $_POST['checking'];?>" />
</li>

That list item is pushed off the page with CSS, and if there is a value in that field, we can assume that it is not a human trying to submit the form:

.screenReader {
	left: -9999px;
	position: absolute;
	top: -9999px;
}

The Validation

Next, we are going to have a conditional statement to determine if the form was submitted or not:

<?php
//If the form is submitted
if(isset($_POST['submitted'])) {

} ?>

Within that conditional, is where we are going to do all of our validation of the required fields. First, let’s check to see if our honeypot captcha form field is filled in. If it is, then we will display an error and not check anymore of the form:

//Check to see if the honeypot captcha field was filled in
if(trim($_POST['checking']) !== '') {
	$captchaError = true;
} else {

} 

So if the captcha field was left blank, we will continue to validate the required fields:

//Check to make sure that the name field is not empty
if(trim($_POST['contactName']) === '') {
	$nameError = 'You forgot to enter your name.';
	$hasError = true;
} else {
	$name = trim($_POST['contactName']);
}

//Check to make sure sure that a valid email address is submitted
if(trim($_POST['email']) === '')  {
	$emailError = 'You forgot to enter your email address.';
	$hasError = true;
} else if (!eregi("^[A-Z0-9._%-]+@[A-Z0-9._%-]+\.[A-Z]{2,4}$", trim($_POST['email']))) {
	$emailError = 'You entered an invalid email address.';
	$hasError = true;
} else {
	$email = trim($_POST['email']);
}

//Check to make sure comments were entered
if(trim($_POST['comments']) === '') {
	$commentError = 'You forgot to enter your comments.';
	$hasError = true;
} else {
	if(function_exists('stripslashes')) {
		$comments = stripslashes(trim($_POST['comments']));
	} else {
		$comments = trim($_POST['comments']);
	}
}

Again, that may seem like a little much, so let’s just take a look at the validation on the name field:

if(trim($_POST['contactName']) === '') {
	$nameError = 'You forgot to enter your name.';
	$hasError = true;
} else {
	$name = trim($_POST['contactName']);
}

If the name field if empty, set a variable that will display the name error and set a flag saying that there was an error on the form. Otherwise, set a variable that will contain the name value from the form.

Sending the Email

Now, we want to send the email if there are no errors:

//If there is no error, send the email
if(!isset($hasError)) {

	$emailTo = 'me@somedomain.com';
	$subject = 'Contact Form Submission from '.$name;
	$sendCopy = trim($_POST['sendCopy']);
	$body = "Name: $name \n\nEmail: $email \n\nComments: $comments";
	$headers = 'From: My Site <'.$emailTo.'>' . "\r\n" . 'Reply-To: ' . $email;

	mail($emailTo, $subject, $body, $headers);

	if($sendCopy == true) {
		$subject = 'You emailed Your Name';
		$headers = 'From: Your Name <noreply@somedomain.com>';
		mail($email, $subject, $body, $headers);
	}

	$emailSent = true;

}

Note: Items bolded are values that you will want to change before implementing.

I personally like to have the contact form submission come from myself. That way, I just setup a filter in Gmail, and I can guarantee that it won’t get caught in my spam filter. The second email is only sent if the user checks the checkbox to send a copy to themselves.

View Entire Custom Page Template

Creating the Page in WordPress

First, you want to upload the contact-form.php page template to your themes folder. Next, you will create the page in WordPress and select Contact Form as the page template.

Adding WordPress page template

Then, just publish your page and you will have your contact form. Well, the form will be usable, but we are going to add in some CSS and jQuery to finish it off.

Styling the Form

I recently wrote an article about styling forms, so we are just going to stick with some basic styles:

.screenReader { left: -9999px; position: absolute; top: -9999px; }
.thanks { background: #F2F3F6; border: 1px solid #7E8AA2; padding: 10px; }

/*****Forms*****/
ol.forms { float: left; list-style: none; margin: 0; width: 100%; }
ol.forms li {
	clear: both;
	float: left;
	margin-bottom: 18px;
	position: relative;
	width: 100%;
}
ol.forms label {
	cursor: pointer;
	display: block;
	float: left;
	font-weight: bold;
	padding-right: 20px;
	width: 100px;
}
ol.forms input, ol.forms textarea {
	border: 1px solid #7E8AA2;
	border-radius: 3px;
	font: inherit;
	-moz-border-radius: 3px;
	padding: 2px;
	-webkit-border-radius: 3px;
	width: 214px;
}
ol.forms textarea { height: 300px; width: 334px; }
ol.forms input:focus, ol.forms textarea:focus { background-color: #f2f3f6; border-color: #ff9800; }
.error { color: #f00; }
ol.forms li .error { font-size: 12px; margin-left: 20px; }
ol.forms li.textarea .error {
	display: block;
	position: absolute;
	right: 0;
	top: 0;
	width: 100px;
}
ol.forms li.screenReader { margin-bottom: 0; }
ol.forms li.buttons button {
	background: #ff9800;
	border: none;
	color: #000;
	cursor: pointer;
	font: 16px/16px "Avenir LT Std", Helvetica, Arial, sans-serif;
	overflow: hidden;
	padding: 6px 3px 3px 3px;
	text-transform: uppercase;
	width: auto;
}
ol.forms li.buttons button:hover { color: #222; }
ol.forms li.buttons button:active { left: -1px; position: relative; top: -1px; }
ol.forms li.buttons, ol.forms li.inline { float: right; width: 460px; }
ol.forms li.inline input { width: auto; }
ol.forms li.inline label { display: inline; float: none; width: auto; }

So drop that CSS in your theme stylesheet and you will see the form start to look much better.

Enhancing the form with some jQuery

I have also already written about creating AJAX forms with jQuery, but I thought I would specifically talk about an AJAX script for a contact form.

First, we want to execute our jQuery when the document is ready and the form was submitted:

$(document).ready(function() {
	$('form#contactForm').submit(function() {

		return false;
	});
});

Next, we want to hide any error messages if there are any and validate any required fields which are denoted with a class of requiredField:

$('form#contactForm .error').remove();
var hasError = false;
$('.requiredField').each(function() {

});

After that, we want to validate that the field is not empty and append an error message if it is:

if(jQuery.trim($(this).val()) == '') {
	var labelText = $(this).prev('label').text();
	$(this).parent().append('<span class="error">You forgot to enter your '+labelText+'.</span>');
	hasError = true;
}

If the field is not empty and also has a class of email, we want to validate that the email address is valid:

 else if($(this).hasClass('email')) {
	var emailReg = /^([\w-\.]+@([\w-]+\.)+[\w-]{2,4})?$/;
	if(!emailReg.test(jQuery.trim($(this).val()))) {
		var labelText = $(this).prev('label').text();
		$(this).parent().append('<span class="error">You entered an invalid '+labelText+'.</span>');
		hasError = true;
	}
}

If there are no errors, then we want to replace the submit button with a loading image:

if(!hasError) {
$('form#contactForm li.buttons button').fadeOut('normal', function() {
	$(this).parent().append('<img src="/wp-content/themes/td-v3/images/template/loading.gif" alt="Loading…" height="31" width="31" />');
});

Note: You will need to update the source of the image to wherever you upload it in your theme.

Finally, let’s submit the form via an AJAX request, slide the form up, and show a thank you message:

var formInput = $(this).serialize();
$.post($(this).attr('action'),formInput, function(data){
	$('form#contactForm').slideUp("fast", function() {
		$(this).before('<p class="thanks"><strong>Thanks!</strong> Your email was successfully sent. I check my email all the time, so I should be in touch soon.</p>');
	});
});

Take a look at the entire script:

$(document).ready(function() {
	$('form#contactForm').submit(function() {
		$('form#contactForm .error').remove();
		var hasError = false;
		$('.requiredField').each(function() {
			if(jQuery.trim($(this).val()) == '') {
				var labelText = $(this).prev('label').text();
				$(this).parent().append('<span class="error">You forgot to enter your '+labelText+'.</span>');
				hasError = true;
			} else if($(this).hasClass('email')) {
				var emailReg = /^([\w-\.]+@([\w-]+\.)+[\w-]{2,4})?$/;
				if(!emailReg.test(jQuery.trim($(this).val()))) {
					var labelText = $(this).prev('label').text();
					$(this).parent().append('<span class="error">You entered an invalid '+labelText+'.</span>');
					hasError = true;
				}
			}
		});
		if(!hasError) {
			$('form#contactForm li.buttons button').fadeOut('normal', function() {
				$(this).parent().append('<img src="/wp-content/themes/td-v3/images/template/loading.gif" alt="Loading…" height="31" width="31" />');
			});
			var formInput = $(this).serialize();
			$.post($(this).attr('action'),formInput, function(data){
				$('form#contactForm').slideUp("fast", function() {
					$(this).before('<p class="thanks"><strong>Thanks!</strong> Your email was successfully sent. I check my email all the time, so I should be in touch soon.</p>');
				});
			});
		}

		return false;

	});
});

Just include it in the head of your document after jQuery, and you are good to go:

<script type="text/javascript" src="<?php bloginfo('template_directory'); ?>/scripts/jquery.js"></script>
<script type="text/javascript" src="<?php bloginfo('template_directory'); ?>/scripts/contact-form.js"></script>

Note: You may need to change the source depending upon where you upload the files in your theme.

Conclusion

View Demo Download Source Files

That’s it! Just upload the files and you’ve got your form. Since you’ve got the code right in front of you, it should be very easy to tweak and add on to. Enjoy!

Share This:
  • del.icio.us
  • Digg
  • Twitter
  • Facebook
  • StumbleUpon
  • Google Bookmarks
  • NewsVine
  • Technorati
  • Reddit
  • LinkedIn

RSS feed of comments for this entry

  1. mate! thanks for this. been looking for this for months. helpful.

    ps : i dont like to use plugins. writing own codes is better “understanding self-coded code is a satisfaction”

  2. I don’t get why you aren’t using a plugin and embedding the contact form functionality directly into the page template? Doesn’t that defeat the purpose and flexibility of plugins? If you change your theme, you have to port over your page template to your new theme. If you develop it as a plugin, it will inject any contact form markup you want into the page dynamically and all you’d have to do is style it differently with CSS. You can also add configuration options to your form via the plugin API. If you implement it using shortcodes, you’d just stick something like “[contactform]” into your page content and the form would render there. I found a lot of overly-bloated contact form plugins out there… which is why I created my own, too ;)

    http://jamescoletti.com/simple-wordpress-contact-form-plugin

  3. @James-
    The reason I didn’t do it as a plugin is because I don’t have that kind of time to add in all the bells and whistles with an admin interface and provide support for the plugin.

    The idea is that you just have the code. It’s easy for a savvy user to update the form for themselves.

    Personally, I like having the actual code to edit instead of passing it into this “black box” and seeing what the plugin produces. I like to have control over every piece of code I can on my site. Maybe not everyone is as anal as me though…

  4. Sure, it looks great. When I apply the CSS to my stylesheet, it moves the “email yourself” check box wayyyyy over to the right.
    Also, what does it actually do with the comments entered? When I test it out, it doesn’t show the comments in any folder.

  5. @timtipper-
    Do you have a link to the page? I could have easily missed some styles when pulling it into a separate stylesheet or something in your stylesheet could be overriding it.

  6. its awesome!

  7. Very nice script, works like a charm. Just a question concerning the style of the error output: Would it be possible to give every input field with a missing/wrong input text a red border instead of display an error-message on the right of the input field via span?

  8. @Olli-
    Sure, you will just want to change this code:

    if(jQuery.trim($(this).val()) == '') {
    	var labelText = $(this).prev('label').text();
    	$(this).parent().append('<span class="error">You forgot to enter your '+labelText+'.</span>');
    	hasError = true;
    } else if($(this).hasClass('email')) {
    	var emailReg = /^([\w-\.]+@([\w-]+\.)+[\w-]{2,4})?$/;
    	if(!emailReg.test(jQuery.trim($(this).val()))) {
    		var labelText = $(this).prev('label').text();
    		$(this).parent().append('<span class="error">You entered an invalid '+labelText+'.</span>');
    		hasError = true;
    	}
    }

    To this:

    if(jQuery.trim($(this).val()) == '') {
    	var labelText = $(this).prev('label').text();
    	$(this).parent().append('<span class="error">You forgot to enter your '+labelText+'.</span>');
    	$(this).addClass('inputError');
    	hasError = true;
    } else if($(this).hasClass('email')) {
    	var emailReg = /^([\w-\.]+@([\w-]+\.)+[\w-]{2,4})?$/;
    	if(!emailReg.test(jQuery.trim($(this).val()))) {
    		var labelText = $(this).prev('label').text();
    		$(this).parent().append('<span class="error">You entered an invalid '+labelText+'.</span>');
    		$(this).addClass('inputError');
    		hasError = true;
    	}
    }

    That should add the class of inputError to the form elements. Then, you can style them accordingly.

  9. @Trevor-
    Thx for your fast reply. Unfortunately it seems I’m incapable to change the CSS the right way. I changed the JS as you told me and added the following to my CSS:

    #contactForm ol.forms .inputerror {
    	border: 1px solid #0000FF;
    }

    But the only error message visible is still the red span-text on the right of the input-fields; there is no border around them. Do you have any idea?

    Thx in advcance!

  10. @Olli-
    Don’t forget that class names are case sensitive. In the JS, I told you to put inputError, but in the CSS you showed, you put inputerror.

  11. @Trevor-
    Damn, of course I forgot – now it works. Thank you very much :)

    • Andrei Gonzales
    • 3.14.2009 at 1:50 pm
    • #
    • Reply »

    While I agree with you regarding your reasons why you didn’t use a plugin (I don’t either – too much overhead when different clients, more often than not, require different contact forms). However, I wonder why you didn’t use jQuery’s Validate plugin for validation?

  12. @Andrei Gonzales-
    I don’t use a jQuery plugin for the same reason I wouldn’t use a WordPress plugin: the plugin adds extra bloat when I don’t really need it, and I want to have completely control over the code.

    Especially when it is something so easy as form validation, why not just do it yourself?

    • RaiulBaztepo
    • 3.28.2009 at 7:05 pm
    • #
    • Reply »

    Hello!
    Very Interesting post! Thank you for such interesting resource!
    PS: Sorry for my bad english, I’v just started to learn this language ;)
    See you!
    Your, Raiul Baztepo

  13. Good thing I bookmarked this article! This tutorial was a big help in rolling out my own contact form that I’m using in my blog.

    Thank you Trevor!

  14. Wow, that was a great tutorial! Thanks I used it on my blog’s contact page!

  15. After setting up this form i didn’t get any mail in my inbox.

  16. I want to use my free gmail account to receive mail through contact us fom

  17. @jitendra-
    You are going to have to provide more information. Are you receiving any errors? Do you have a url to the page? Is it getting caught in your spam filters?

  18. Great tutorial, thanks Trevor. I also like to see what’s happening on the page and have full control so this is the perfect solution.

    I have one problem I was hoping you could shed light on – the form isn’t sliding up at the end. ie .slideUp isn’t firing in the jquery which is odd because the callback function adding the ‘thanks’ paragraph in before it is working! I’m using the latest jquery release 1.3.2 instead of the one packaged with your files but I don’t think that would affect this. Any ideas you have would be greatly appreciated. Thanks :)

  19. @bitka-
    Did you have a link so that we can see the error?

    • Maria Mingosmo
    • 5.12.2009 at 8:02 pm
    • #
    • Reply »

    Hi trevor

    I’ve already used the other form mailer you created in this website. With a few changes and it works like a charm. Sorry but I had to ditch the ajax stuff.

    Now about this one (that’s for a wordpress project), will it work with a custom thank you page (because of conversion tracking)?

    I think that instead of showing some code after the form is submited, we can do a redirect to the thank you page, am I right? And will this enable me to put contact records in a database without any wordpress conflits?

    Sorry if I ask to much.

    Thanks in advance Trevor

    Maria M.

  20. @Maria Mingosmo-
    You could always just add a parameter in the URL so that it would track the conversion.

    So instead of /contact/, try /contact/?thanks

    If that isn’t enough for you, then you could do a redirect before any headers are sent.

    • Maria Mingosmo
    • 5.13.2009 at 12:38 am
    • #
    • Reply »

    I really need a separate Thank you page (really need google conversion tracking on that one), so i’ll try to redirect users after all the form fields are validated. I will let you know how it worked out.

    Thanks for your kind reply. Keep on coding, I’m lovin it! ;)

    Cheers

    Maria M.

  21. Great work! But how about spam? Many contect form plugins have anti-spam sistem

  22. @future-
    The form is already using honeypot captcha, and you could easily add in another method.

  23. Hi Trevor,
    After going thru so many contact form plugins I came accross your tutorial and I chose to implement your contact form. What a surprise! :).
    Thank you very much for sharing your work. However, I have one question. How to make the form slide up. It doesn’t do it. However, the console with firebug shows the correct response but no refreshing of the page. What did I do wrong?
    Thank you,
    Stu
    P.S. my site is wordpress.stumillersmovers.com

  24. @stu-
    You know, that’s weird, bitka was having the same problem. I don’t see anything in the code that would cause a problem.

    Maybe try only using the $(‘#contactForm’) selector. Maybe try switching your doctype to be strict (that’s the only real difference I see between my example).

  25. @Trevor-
    Thank you for your suggestions, but still no sliding up and I realized that even your demo is not sliding up…?
    How to simply modify your code to just refresh the form?

  26. @stu-
    Weird, it was definitely sliding up before. So when you say refreshing the form, you just want to remove the values from the field? Just try setting the value attribute to nothing, that should do it.

  27. @Trevor-
    This is how I fixed it:

    if(!hasError) {
    $('form#contactForm li.buttons button').fadeOut('normal', function() {
    $(this).parent().append('');
    });
    var formInput = $(this).serialize();
    $.post($(this).attr('action'),formInput, function(data){
    $("form#contactForm").before('Thanks! Your email was successfully sent. I check my email all the time, so I should be in touch soon.');
    });
    $("form#contactForm").slideUp("slow",function() {});
    }

    and it works like a charm. Thank you!

  28. I forgot to mention that there needs to be a in the to be able to slide. If there is no div, no sliding…

  29. I meant a tags in the tags and it works great…Go figure :)

  30. Still missed it! I spent too much time in front of a computer…. I meant div tags. There need a tag and it works great.

  31. It would be good if add spam prevention feature.

  32. @Guresh-
    There is already honeypot captcha added to the form. You could easily add in something else as well.

  33. Hi, thanks a lot for such a beautiful tutorial, i have a question,

    could you please show me how can i add a text field that will validate an URL?

    thanks

  34. @akber kabir-
    You will want to validate the field similarly to how the email address is validated, you will just need to use a URL regular expression.

  35. Trevor,

    I’ve gotten your code to work just fine when on a page.

    However, I’m attempting to stick this in my index.php file… and obviously its not working because there is an issue with the url of the form action.

    what do you suggest i use for that form action url?

    On click it says “thanks” etc etc, but its really not working because it wont send. (but it does send when in a page)

  36. @kristian-
    The way that I have coded the form, you should always have the form action be the current page that it is on.

    So if you have added the form onto the index.php file, then you want the form action to be index.php.

  37. Thank you so much for your hard work and the great contact form. I am currently using it on an upcoming project and was wondering if you could help me implement a drop-down option menu? The user selects a subject for the inquiry and this selection determines which email address the message gets sent to.

  38. @Larry-
    Sure you could easily add in a select element that adjusted the subject of the email. Just add in the HTML and adjust the PHP to accommodate the new field.

  39. Ok, after a little research this is the basic code I’ve come up with. This is the first time I’ve tried to do this and my PHP knowledge is very basic, so please bare with me.

    HTML for form:

    General
    Booking
    Press

    PHP to process form:

    switch($_POST['subject']){
    	case 'general':
    		$emailto = 'info@example.com';
    	break;
    	case 'booking':
    		$emailto = 'booking@example.com';
    	break;
    	case 'press':
    		$emailto = 'press@example.com';
    	break;
    }

    Does this make sense?

  40. @Larry-
    Makes sense to me

  41. @Trevor-

    I’m not sure why the HTML wouldn’t post. I wrapped it in the proper tags.

  42. @Larry-
    Like pretty much all blogs, you must encode the open bracket < to be &lt;

  43. Great article, and even contains validation ;-)

    The only problem is that I want the error messages to appear underneath the relevant inputs. With the appends used, is this possible?

    Thanks.

  44. @Barton-
    Absolutely. If you modify the css for the error class, you can get them to display however you want.

  45. Thank you for writing this post about creating your own contact form, without having to use a plugin.

    Question for you: I have a site that requires more than 1 contact form, with different fields on each form.

    Are there any options you recommend for implementing your template for use in multiple forms on a site?

  46. @Deborah-
    Sure, just create multiple page templates. Then select the appropriate template for each page with the form on it.

  47. thank.you!!!

  48. Awesome template, it was exactly what I was looking for, I also dislike using plugins as well.

    BTW, you don’t have a closing tag in the “View Entire Custom Template” link in your tutorial found at:

    There was an error submitting the form.

    Thanks!

    Edit: Spaces added.

  49. @Rhys-
    I’m not sure what you mean. I don’t see where there is a missing closing tag.

  50. I created an e-mail field in the theme panel, but the contact form won’t recognize the field.
    Does the form accept the options call in the e-mail field ? i.e. if I place instead of the e-mail address :

    It is not working and I have already inserted the code to enable the option in the contact page template.
    Any help will be appriciated

  51. @Nort-
    I’m not sure what you mean. Can you explain in more detail?

  52. sorry code didn’t show :

  53. thanks for fast reply. For example, you have to change the e-mail address where you want the form to send the e-mail in the contact-form.php file.

    Instead I created a custom field in the theme options panel, so that my client can change the contact e-mail whenever he wants without touching code.
    However, the form does not understand that field, even though I think I have inserted the code correctly, and I am calling the theme options in the contact page template….

  54. @Nort-
    So are you accessing the option using get_option? It seems like that should work fine.

  55. yes, I am accessing the option and everything, normally I know how to do it. The form works fine if the e-mail is inserted directly.
    I have no idea why that’s happening, maybe because of the script ?

  56. @Nort-
    So if you just output the option on the page it works fine? Without seeing any code, I can’t give you any reason why it wouldn’t work.

  57. Your code helped me understand how to adapt my current contact form into a Wordpress page. I had everything right except for the permalink code in the action and the way you persisted the values.

  58. Hi,

    What a wonderful tutorial. It is great.
    However, I am curious where you put the conditional code in your real demo?

    You guide the audience as shown in your contact-form.php, that the following will be included:
    //If the form is submitted
    if(isset($_POST['submitted'])) {

    But when I see your demo page and display your source code, you just start from the following:
    <form action="

    Can you explain the difference between what is in your guidance and your own usage?

    Also (another question), if you have :
    If have post, while have post, the-post,

    After click the SUBMIT button, it will display a post, instead of the message (either the red error message or thank you message), as shown in your tutorial.

    How to solve these problem?

    Thank you Trev!

  59. @Andrew-
    I’m not sure what you are asking. If you look at the PHP file that you can download, you will see where that code is.

    Do you have a link to see the problem you are having?

  60. Thanx for quick response, and sorry for the 2 questions as I found the answers already.

    I realized that HTML does not display some PHP codes. Also I modified the url of the js files, now they works.

    But the $emailTo = ‘me@somedomain.com’; doesnt work. Yes of course I have replaced it with my own email address, but still doesnt work as I never receive email after click the EMAIL ME button. Can you explain why? Bytheway, I dont have link, I just do experment locally with wamp.

    And also (another question), at this part:
    if($sendCopy == true) {
    $subject = 'You emailed Your Name';
    $headers = 'From: Your Name ';
    mail($email, $subject, $body, $headers);

    Should I replace noreply@somedomain.com with my email? Please kindly clarify.

    Thanks once more, Trev

  61. if($sendCopy == true) { $subject = ‘You emailed Your Name’; $headers = ‘From: Your Name ‘; mail($email, $subject, $body, $headers);

  62. @Andrew-
    Are you sure you have mail to work setup locally?

    Unless you want it to come through in the email as noreply@somedomain.com, I would change it.

  63. Trev, I use Hotmail. So I replace the me@somedomain.com, with my email @hotmail.com.

    Is it ok to use hotmail or yahoo?

    For the noreply@somedomain.com, can I use the same email address of mine?

    By the way, if sendcopy is checked: if(isset($_POST['sendCopy']), how do you (the code) use the email address supplied into the box for sending email.

    Thanks so much for your quick response. Only, if possible, be more detail. Thanks again.
    Good luck Trev!

  64. @Andrew-
    You can use whatever email provider you want; it is using the server to send the mail.

    The code is already in place to send a copy to the person if they check the box.

    • ahmed hamouda
    • 9.8.2009 at 6:27 pm
    • #
    • Reply »

    It is fantastic but It doesnt deliver mails from domains
    only from hotmail etc but no mains from user@example.com
    I wonder how to fix it.

  65. @ahmed hamouda-
    What do you mean it doesn’t deliver mail from domains? It works perfectly fine when I test it. Are you testing it locally?

  66. I meant that when the sender’s email aint from an official web mail server it doesnt arrive
    f.e when I sent an email and the sender email was example@9.cn it didnt arrive
    when I used sth like my domain email
    admin@ahmedhamouda.me it didnt arrive.
    Even with the Bug you made a wonderful Job ..

  67. My bad
    I receive my messages in a gmail account
    and I use thunderbird and it considered all the emails like spam so it didnt appear in the thunderbird inbox
    Agian dude you are awesome xD
    May be I will write about it in my arabic blog after translating your post ofcourse
    Thanks alot for this awesome trick
    Best Regards ..

  68. I think this is great. Just having an issue.

    For some reason when I try to test this, the email does not come to my inbox. I checked my spam folder also, just in case. Nothing there either.

    I did verify my email was working by installing a contact form plug-in. It worked, I just cannot get this to send the email to myself.

    Am I doing something wrong possibly?

    Thanks,

    David

  69. @David-
    Not sure what to say, there must be something going on with your setup. Can you get regular PHP mail to work on your server? That’s basically all this is doing.

  70. Yes it works fine.

    I even had a different script that worked but not within the wordpress environment.

    So I found this and it seems to be a step closer, I even get the confirmation message. Just no email received…

    Wierd.
    - David

  71. @David-
    Do you have Firebug? What do you see in the POST request?


  72. comments Hola Senior
    contactName David
    email *my correct email address*
    submitted true

  73. @David-
    And you have updated the $emailTo variable in the script to send to your email address?

  74. @Trevor
    Yes, I have.

    $emailTo = 'MYEMAIL@MYDOMAIN.COM';
    $subject = 'Contact Form Submission from '.$name;
    $sendCopy = trim($_POST['sendCopy']);
    $body = "Name: $name \n\nEmail: $email \n\nComments: $comments";
    $headers = 'From: My Site ' . "\r\n" . 'Reply-To: ' . $email;

    Kinda hard to show it without giving the world my email address…

    -D

  75. This is highly dumb. Instead of coding a one-piece HTML / PHP tag soup, use a plugin. It’s more flexible, more easy to share.

    Duh.

  76. @Ozh-
    Wow, thanks for contributing to the discussion.

    I am not happy with the code that the contact form plugins create, and I prefer to have 100% control over the code being output on my site. This is why I would rather write the code myself.

  77. Good work Trevor, great post.

    RE: Ozh’s comment:

    Mate it’s your choice if you do a plugin or you post on how to do a contact form template. The good thing is that you have published it for anyone to use.
    If people cant use your code, they have a choice to use one of the other form plugins.

  78. Hi, thanx for the great tut. I am just working on an implimentation, and thing arose. Since 2005 umlauts and a lot other utf entities can be a part of domains as well as e-mail addresses. now, i want to use you’re form on a german site, ergo umlauts are possible to occur.
    I was trying to find a reg-exp. to validate e-mails with umlauts, etc. but could not find anything useful yet.
    Do you have any idea where to look for such?

    Thanx in advance.

  79. @phil-
    Not sure I know the answer to that question. I would try Googling around and seeing what you can find; I’m sure someone else has run into a similar problem.

  80. Fabulous solution! Thank you!

  81. Just wanted to say thanks for this Trevor, it’s helped me a lot today.

    And well done for being so patient with your commenters :-)

    Maybe some of the issues people are having with receiving mails could be resolved by adding a more fulsome set of mail headers?

    return-path, x-mailer, x-sender-ip etc and I’ve seen issues with mail needing to specify ini-set.

    Hope that’s useful to someone. Thanks again.

  82. @David-
    Awesome, thanks for the tips. Hopefully that will help some people out.

  83. thank you for the code and tips, will test this out.

  84. Trevor! thank you for this, I was able to hard code it to a page. however my form doesnt seem to be sending out emails. I added my email address to the code but it doesnt seem to work.

    
    		if(isset($_POST['submitted'])) {
    
    	//Check to see if the honeypot captcha field was filled in
    	if(trim($_POST['checking']) !== '') {
    		$captchaError = true;
    	} else {
    
    		//Check to make sure that the name field is not empty
    		if(trim($_POST['contactName']) === '') {
    			$nameError = 'You forgot to enter your name.';
    			$hasError = true;
    		} else {
    			$name = trim($_POST['contactName']);
    		}
    
    		//Check to make sure sure that a valid email address is submitted
    		if(trim($_POST['email']) === '')  {
    			$emailError = 'You forgot to enter your email address.';
    			$hasError = true;
    		} else if (!eregi("^[A-Z0-9._%-]+@[A-Z0-9._%-]+\.[A-Z]{2,4}$", trim($_POST['email']))) {
    			$emailError = 'You entered an invalid email address.';
    			$hasError = true;
    		} else {
    			$email = trim($_POST['email']);
    		}
    
    		//Check to make sure comments were entered
    		if(trim($_POST['comments']) === '') {
    			$commentError = 'You forgot to enter your comments.';
    			$hasError = true;
    		} else {
    			if(function_exists('stripslashes')) {
    				$comments = stripslashes(trim($_POST['comments']));
    			} else {
    				$comments = trim($_POST['comments']);
    			}
    		}
    
    		//If there is no error, send the email
    		if(!isset($hasError)) {
    
    			$emailTo = 'queesy@gmail.com';
    			$subject = 'Contact Form Submission from '.$name;
    			$sendCopy = trim($_POST['sendCopy']);
    			$body = "Name: $name \n\nEmail: $email \n\nComments: $comments";
    			$headers = 'From: My Site ' . "\r\n" . 'Reply-To: ' . $email;
    
    			mail($emailTo, $subject, $body, $headers);
    
    			if($sendCopy == true) {
    				$subject = 'You emailed Your Name';
    				$headers = 'From: Your Name ';
    				mail($email, $subject, $body, $headers);
    			}
    
    			$emailSent = true;
    
    		}
    	}
    } ?>
    
    		Thanks,
    		Your email was successfully sent. I will be in touch soon.
    
    			There was an error submitting the form.
    
    		<form action="" id="contactForm" method="post">
    
    				Name
    					<input type="text" name="contactName" id="contactName" value="" class="requiredField" style="margin-left:10px;"/>
    
    				Email
    					<input type="text" name="email" id="email" value="" class="requiredField email" />
    
    				Comments
    
    				<input type="checkbox" name="sendCopy" id="sendCopy" value="true" />Send a copy of this email to yourself
    
    				Submit »
    
    

    it submits just fine says it sent, but i dont see it in my inbox =(

  85. i can get it to work HERE: http://ampersandbox.net/?page_id=130

    but not HERE: http://ampersandbox.net/?pg=about

    was hoping i could do it outside a page template…. didnt think there would be much difference…. =(

  86. @Kevin-
    I can’t really debug why emails aren’t sending. You may have to check your email settings on your server.

  87. @Trevor-
    nevermind , basically it did not work because i tried to hard code it into my indexphp. showed up fine but would not send emails so i just made a page template liek you suggested

  88. Hello Trevor,

    I love your contact form but can’t for the life of me get it to call your .Js file. Can you take a look at scottbarrettdesign.com and let me know of any problems you can find? It submits the form via email just fine but without the bells and whistles of the js. Thanks in advance for your assistance.

    Skot

  89. @skot-
    I don’t see where in your page you are including the jQuery to validate the form.

  90. @Trevor-
    Thanks for the quick response. I’ve been swapping js files and my header.php so much, I had the wrong one in at the time I asked you to check. Its in there now but still no results. Please let me know if you can find the problem. Thanks for the help, Trevor.

    Skot

  91. @skot-
    Looks like you are missing a single quote:

    Error: unterminated string literal
    Source File: http://www.scottbarrettdesign.com/wp-content/themes/sbdNash/js/contact-form.js
    Line: 21, Column: 159
    $(this).parent().append(<img src="http://www.scottbarrettdesign.com/wp-content/uploads/2009/11/loading.gif" alt="Loading…" height="31" width="31" />');
  92. @Trevor-
    Thanks for the efforts, Trevor. Still can’t get it to display correctly though. If you get a chance, please try taking one more look and I’ll leave you alone \o/

  93. @skot-
    It looks like you are using jQuery with noConflict. If you look at the way that you are loading the cycle plugin:

    jQuery(document).ready(function($) {
    	$("#rotator").cycle({
    	    fx: 'fade',
    	    timeout: 3000,
    	    speed: 1000,
    	    pause: 1,
    	    fit: 1
    	});
    });

    You will need to do the same for the contact form.

  94. Thanks a million, buddy. Look forward to more tuts from you. Consider you bookmarked ;)

  95. how about adding checkboxes,
    and none required fields?

    everything else works, but i cant get it working…

    Zumba toning WORKSHOP
            <input type="checkbox" name="earlybird"   value="147.50 "  onclick="this.form.total.value=calculateTotal(this);" />
          "Early bird"  tarief a 147.50 Euro
    
          VES ZIN Member a 147.50 Euro
    
          Normaal tarief a 180 Euro
    
          Extra  
    
          geen gebruikmaken van lunch buffet
    
          wel gebruikmaken van lunch buffet incl. koffie/thee en melk a 11.- Euro
    
            Totaal:
  96. cant get the checkboxes to show either…

    http://www.pasteall.org/9390

  97. @peter-
    I’m not sure what you are asking.

  98. how do i get to see if someone hits a checkbox, and especially what checkbox

    and the content of a autogenerated textfield

    i need to get those values into the email

    thanks in advance!

  99. @peter-
    You just need to use the name attribute of the form fields to access the data. Then, you can access them in the $_POST array.

  100. http://www.pasteall.org/9411

    nothing happens…

  101. @peter-
    I’m sorry, I can’t walk every person through their specific issues in their forms. If you are interested in more in depth help, you can hire me by contacting me directly.

  102. Hi Trevor,

    I just implemented your template and it works great.
    I have just one question: I’m using it in a Portuguese website and I’m getting problems with the text encode when I receive the emails submitted.
    Special characters – accents, cedilla, etc – aren’t displayed correctly. And line breaks appear with symbols (they are displayed by the entity name).
    Do you know how can I add character encoding to the sent emails?
    Thanks!

  103. Hi Trevor,

    I’ve been looking so much for a way to manage forms WITHOUT having to use a plugin and have total control of the code. So, first of all, thanks for putting up the only tutorial on the whole web about such a thing.

    Sadly, I too can seem to be able to send emails from WP. I am at MediaTemple and the server send it fine when outsdode of WP. I just copied your template file, changed the email address, linked the JS, but don’t get emails.

    I need this so much to work, as it’s the laste step vefore I publish my site, and if I can’t get a simple form to send an email, I cannot publish the site.

    Strangly enough, at some point I recopied all the code from the tutorial, and at some poitn it did manage to send teh email. So that mean that something made it work, but now, again, without any change, it just doesn’t send anything anymore.

    If you want I can provide a link to the development site, but I prefer to send it to your mail (don’t want to make it public ’til the site is in dev phase).

    Thanks for the help.

    Gian.

  104. @Ana-
    You can pass in additional headers in the mail function to specify the charset.

    @Gian-
    Does the email send when you are not using JavaScript? Is it getting caught in your spam folder?

  105. Great sample code. Thank you.

    Do you have any guidelines for adding a type=FILE field to this form? I tried to do so and have run into some issues:

    1) The incoming type=FILE field on my contact form is optional, but if I do generate errors on other required fields on the same form then I am unable to refill the contents of the type=FILE field – as your code does for the other fields in your example.

    I believe this is due to an HTML security feature to prevent websites from pre-filling FILE fields – but in my case if a user fills out a form – including selection of a local file to upload in a type=FILE field – and then clicks SUBMIT, and then subsequently gets an error on some field other than the FILE field, then I am unable to refresh the type=FILE field and they will need to be reminded that they need to re-select their optional FILE field that they had filled in the first time around.

    In other words, upon detecting errors in your current contact form you currently always refresh all incoming fields so that the user does not need to re-enter them when one or more edit/missing errors are detected. But type=FILE fields cannot be refreshed in this manner. And since my type=FILE field is optional then I cannot always simply check that it was filled in.

    How would you handle that issue?

    2.) As I am just creating this new contact form with a type=FILE field I am noticing that when processing the incoming form data that I am unable to access the path or file contents in either $_FILES['fieldname'] ['name'] or $_FILES['fieldname'] ['tmp_name'].

    I can, however, access the uploaded file’s name in $_POST['fieldname']

    Do you know of any reason why these values are not accessible when I am processing the incoming form? I successfully can access all the other incoming form fields, as well as the actual file name of the type=FILE field, just not the full pathname nor the file contents itself.

  106. @Joe-

    I just figured out Part 2 of my issues: I couldn’t access the file data because I had not included the pesky “enctype=multipart/form-data” on my FORM statement.

    I still could use advice on my issue #1 – how to handle an optional type=FILE field if errors occur on other fields

  107. @Joe-
    I guess you could upload the file to the server regardless if there are errors in the form or not.

  108. nice, thanks man

  109. Hey, nice tutorial, I managed to make the form work but i have a slight problem. When I send out a email, I receive 2 identical emails inside my inbox. Do you know what is causing this?

    Thnx

  110. @Alex-
    Are you checking the box to send an email to yourself?

  111. No, I am not. Simply, when I press the send button in the recipient`s inbox i receive 2 identical emails. I checked the code but it`s nothing wrong.

  112. @Alex-
    Do you see 2 requests in the Firebug console? Is it submitting the AJAX request and then the regular request?

    If not, you may want to talk to your host about it.

  113. Hello Trevor,
    I really like this code. But there is a little problem if I try to expand the abillity to send emails to different recipients.
    In WordPress I use the Custom Fields to set an email adress. I call the page using your template as url with parm:
    …/?mailempfaenger=” target=”_blank”>Mail an den InserentenIn your template I can read this by using the following code:
    $empfaenger = htmlspecialchars($_GET["mailempfaenger"]) . '';
    If I echo it in your code before displaying the form, the email-adress is shown correctly.
    I ‘ve set the variable $emailTo to $empfaenger
    As if the mail was not sent, I tried to echo the variable $emailTo. It seemd to be empty. Also I tried to set it’s value by using:
    $emailTo = trim($_GET['empfaenger']); and
    $emailTo = trim($_POST['empfaenger']);
    Both did not work.
    Do you know, how I can retrieve the value from inside your script, so I can use it as email adress where the form should be sent?
    Thanks a lot.
    Torsten

  114. @Torsten-
    I am not sure what you are trying to do here. This is just regular PHP here, nothing fancy, so I’m not sure why your code isn’t working.

  115. Hi, Trevor.
    Thanks for great tutorial,very helpful.
    Please explain me how to change the style of submit button. I want to use only “” without “” and I don’t wanna use the tag “” . When I delete all unnecessary tag mail stop delivering. I think there need to change contact-form.js file but I don’t know HOW.
    Please help me!
    Sorry for my english.

  116. Oops!
    I want to use only “input” without “button” and I don’t wanna use the tag “li” .

  117. @Denys-
    Not sure what you mean that you don’t want to use an li tag, but here is the code you would need to modify to use an input instead of a button:

    $('form#contactForm li.buttons button').fadeOut('normal', function() {
    	$(this).parent().append('<img src="/wp-content/themes/td-v3/images/template/loading.gif" alt="Loading…" height="31" width="31" />');
    });
  118. @Trevor-
    Thank you! I know that but dont know how to modify.
    If I delete li tag in html i must modify this line in js file
    $('#contactForm li.buttons button').
    My html for submit button looks like

    How I should modify my js code for this html?

  119. oh mine God!!!Sorry.
    My html for submit button looks like
    ‘input type=”submit” name=”button” id=”button” value=”Submit” />’

  120. @Denys-
    Just use the id of your submit button.

  121. Trevor delivery isn’t working.
    I’m trying to use “form#contactForm #button”, “#button”, “button”.

  122. @Denys-
    I don’t know what you mean. Where are you trying to use this? What’s not working? Does the form submit? If you want help, you need to be more descriptive and clear about what is not working or what you are trying to accomplish.

  123. I had a ready html form, I decided to add ajax in accordance with your tutorial. Everything has changed, except the button submit. Letters come on a box only when the button html-code is not changed. If I try anything to change letters stopped coming to the box, the form sends but I do not receive letters. How it is interconnected I do not understand.

  124. Hello Trevor,

    well, of course, it’s regular PHP. But the Problem is, I don’t know, why the code $empfaenger = htmlspecialchars($_GET['mailempfaenger']) . '';
    echo $empfaenger;
    works if I place it in the beginning of your script (line 6) but don’t if it’s placed later (after the line 50). Do you know which mistake I’ve made?
    I thought “$_GET” is superglobal, so it should work everywhere?
    Thanks for your help.

  125. @Torsten-
    I don’t see why it wouldn’t work.

    @Denys-
    Can you provide a link?

  126. @Trevor-
    Thank you! I think this help

  127. @Denys-
    The form submitted fine for me.

  128. For me too, but mail doesnt sending. With your design all fine but with some trouble. I dont know why.

  129. @Denys-
    You should try contacting your host then or double check the PHP code to make sure you are sending to the right address.

  130. Maybe you dont understand me. The form stop sending only after two changes. 1) Styling the SUBMIT button and 2) changes in js file in this lines :

    $('form#contactForm li.buttons button').fadeOut('normal', function() {
    	$(this).parent().append('');
    });

    Before this mail is coming. In both methods form the form is submitted. I think host and PHP isnt guilty.

  131. @Denys-
    Sorry, I can’t debug every individual problem. If you would like me to, then you can hire me.

  132. Hi Trevor!
    I have the problem with error messages. Message show text but dont show label name at the end of message.
    Looks:

    You forgot to enter your .

    I dont touch js file. How fix it?
    Thanks.

  133. @Denys-
    It depends on your markup. It is grabbing the value from the text in the label.

  134. @Trevor-
    All your labels is saved. I dont change label name.

  135. @Denys-
    I can’t help you if you don’t provide more details or a link.

  136. @Trevor-
    See this link
    Tell me can I delete your js validation and use some plugin for that.What and how I need to change in contact-form.js ? Thank you!

  137. @Denys-
    You completely changed the markup of your form, which the JavaScript validation depends on.

  138. Trevor, I’ve been digging around in the css for a while and for the life of me I can’t figure out how to get rid of the border around the checkbox.

    It shouldn’t be there since the border style only applies to ol.forms input, ol.forms textarea.

    Also, I’m having trouble getting the Submit button to align square in the center of the form. I’ve tried text-align: center, tried setting the width to a fixed pixel number and still no luck.

    Thanks.

  139. @Trevor-
    I understand. How to delete your javascript validation and keep on javascript submit? Thanks.

  140. @Julie-
    A checkbox is an input elements, so it will inherit styles being applied to input elements. Try using text-align: center on li.buttons.

    @Denys-
    Just delete the JavaScript then. There are a million form plugins out there; it seems like mine doesn’t suit your needs.

  141. I know about all plugin out there,but at this time sending email normally only your form. At this time I need some changes with submission and validation. For validation I want to use some plugin like “jquery validation”. I cant delete your javascript because that delete a function “submit without refreshing page”. I’m truying delete this lines:

    var hasError = false;
    $('.requiredField').each(function() {
    	if(jQuery.trim($(this).val()) == '') {
    		var labelText = $(this).prev('label').text();
    		$(this).parent().append('You forgot to enter your '+labelText+'.');
    		hasError = true;
    	} else if($(this).hasClass('email')) {
    		var emailReg = /^([\w-\.]+@([\w-]+\.)+[\w-]{2,4})?$/;
    		if(!emailReg.test(jQuery.trim($(this).val()))) {
    			var labelText = $(this).prev('label').text();
    			$(this).parent().append('You entered an invalid '+labelText+'.');
    			hasError = true;
    		}
    	}
    });
    if(!hasError) {

    After this form submiting always when push on submit button even when form is cleared. Im just want to use your form with javascript submition but with my plugin validation. How to do this? What lines I must delete,change? Thank you!

  142. @Denys-
    There is a limit to how much support I can provide to every person; you are basically asking me to do your work for you. If you are interested in that, you can hire me.

  143. I’m asking because dont understand javascript. Thanks for form.

  144. Hi,

    I’ve been looking for a form with a send to yourself feature for ages, so excellent to find this site. Just wanted to check to see if I can use this form for a non wordpress website? Guessing as it is not a plug in then it should be ok.

  145. @Keith-
    Yeah, you should be able to use it on just a regular PHP site too.

    • Paul Versteeg
    • 1.16.2010 at 4:04 pm
    • #
    • Reply »

    Very nice! Thank you

  146. Trevor, I appreciate your input. I had some things that apparently override the “text-align: center” for the buttons. Got rid of that – now it works.

    Another question – I’m now trying to implement a jQuery hide/show function where the “billing address” section is hidden unless the user checks a checkbox that says “my billing address is different than my mailing address”. I’m so new to php and jQuery that I’m really stuck in the basic syntax.

    This is what I have written in the .js file:

    jQuery(document).ready(function () {
    	jQuery('$billAddress').hide();
         	jQuery('$billShow').click(function() {
       	           jQuery('$billAddress').hide();
       					if(jQuery('$billAddress').css('display')=='none') {
                             jQuery('$billAddress').show();	} else {
    	        jQuery('$billAddress').hide();		   }
     	 });

    Now, I have no idea how to tie this to the checkbox in the .php file.. I’ve started with your basic checkbox from the contact form but I don’t know where to go from there..

    
    <input type="checkbox" name="billShow" id="billShow" value="true" />My billing address is different from my mailing address

    Thanks so much for all your help!
    Julie

  147. Sorry.. it seems part of my code was cut off.. it’s the same as your contact form checkbox code, only the id is changed to “billShow”.

    • Paul Versteeg
    • 1.17.2010 at 12:23 pm
    • #
    • Reply »

    hi,

    When submitting your great form, i get two “thanks” messages displayed and the email is also sent twice.

    I’ve checked for any duplicate code, but I can’t seem to fix it; any idea what i’m doing wrong??

    thanks,

    Paul

  148. @Julie-
    Your syntax is not correct.

    jQuery('$billAddress')

    Is not going to select anything. You should review the available selectors.

    @Paul Versteeg-
    Maybe you are getting a JavaScript error somewhere after you submit the form. So it sends the email via AJAX and then without AJAX. Not really sure what else it could be.

  149. Trevor, thanks for pointing me in the right direction. After some more studying and Googling I found this to have worked for me:

    jQuery(document).ready(function() {
    	$('form#ftpForm .billDiff').click(function() {
       		$('form#ftpForm .hideThis').toggle("slow");
      	});
    
    });

    Thanks again!

  150. I want to thank you too, your method is really great, already use it on my blog. Great post, great contact form.

  151. Trevor, I hate to keep bugging you but I’ve Googled and read the web all day and I’m no closer to a solution.

    My problem is now that the “Billing Address” fields are hidden on page load by the .js, if there is an empty field and the user submits the form, the page reloads with the error messages appropriately, but the “Billing Address” fields stay hidden. When I click the checkbox to show these fields, the errors are there.

    Do you have any idea, how to save the “checked” state of the checkbox on browser reload (thus keeping the hidden fields visible with errors), if the form doesn’t submit due to missing fields?

    Thanks so much for your help!

  152. @Julie-
    There are various methods to accomplish what you want to do. I would probably check to see if the checkbox is checked before hiding the fields with JS.

  153. I’m still a bit confused, though.. I thought this bit of code:

    would retain the checkbox’s checked state when the form was attempted to Submit (as it also kept the values inside the text fields)..

    if that’s true, then it must be something in my JS file that overrides that?

  154. sorry.. :)

  155. @Julie-
    I can’t really comment on what your form should do without seeing it. I have no idea how you have coded your form.

  156. thank you very much, it’s awesome tutorial

  157. i like this article followed all the steps , skipped jquery part.

    basic question , when i click on submit button .

    i get 405 error resource not found .

    action=”" still does not work.

    if i remove
    if(isset($_POST['submitted'])) {

    works fine .
    thanks

  158. @ven-
    Sounds like you may need to contact your host about that error. Without seeing the link to your page, I can’t help at all.

  159. ok . now all my pages are redirecting to static home page. i think this is related with wordpress settings.

  160. Wow that’s a great tutorial! Thanks for sharing!
    I have a question: is it possible to send the message to multiple e-mail addresses?
    Do you have to separate the addresses with a comma or something?
    I am asking this because I implemented the form into a wordpress theme and I am grabing the email address from the wordpress admin area: I created a custom function that adds me a field in the admin area where I can add the email address, and isted of calling $emailTo, I call for my custom function:

    $headers = ‘From: My Site ‘ . “\r\n” . ‘Reply-To: ‘ . $email;

    mail($custom_function, $subject, $body, $headers);

    Everything works just perfect if I only add one email address. But if I add more than one address, I won’t recive any emails… I separated the email with a comma.
    Any ideeas how this might be worked out?
    Thanks in advance!

  161. No worries! I solved the pb: there has to be a space in front of the comma:

    name@domain.ex , name@domain.ex

    Thanks again!

    • 2.26.2009 at 7:01 am
    • #
    • 2.26.2009 at 11:12 am
    • #
    • 2.26.2009 at 9:34 pm
    • #
    • 2.27.2009 at 5:22 am
    • #
    • 3.1.2009 at 11:19 am
    • #
    • 4.9.2009 at 10:58 am
    • #
    • 5.28.2009 at 11:10 am
    • #
    • 7.5.2009 at 2:52 pm
    • #
    • 8.6.2009 at 12:16 pm
    • #
    • 8.8.2009 at 10:56 pm
    • #
    • 8.10.2009 at 11:08 am
    • #
    • 8.11.2009 at 6:16 am
    • #
    • 8.11.2009 at 6:16 am
    • #
    • 8.11.2009 at 8:30 am
    • #
    • 8.11.2009 at 11:20 am
    • #
    • 8.18.2009 at 8:37 am
    • #
    • 8.24.2009 at 2:43 am
    • #
    • 9.9.2009 at 8:40 am
    • #
    • 9.22.2009 at 3:47 pm
    • #
    • 9.26.2009 at 4:14 am
    • #
    • 9.26.2009 at 11:50 am
    • #
    • 9.27.2009 at 11:55 am
    • #
    • 10.2.2009 at 8:44 am
    • #
    • 10.28.2009 at 10:36 am
    • #
    • 11.4.2009 at 10:33 am
    • #
    • 11.13.2009 at 7:57 pm
    • #
    • 12.17.2009 at 7:58 am
    • #
    • 12.18.2009 at 12:05 pm
    • #
    • 1.5.2010 at 3:13 am
    • #
    • 1.5.2010 at 10:57 am
    • #
    • 2.5.2010 at 7:12 pm
    • #

Speak Your Mind

* Denotes Required Field

  1. To post code snippets, use <pre><code>YOUR CODE HERE</code></pre>
Me, Trevor Davis. My blue steel face…

Hi, I’m Trevor Davis

I’m a 25 year old Front-End Developer living in Arlington, VA. I work full-time at Viget Labs and freelance on the side.

I specialize in CSS, HTML, jQuery, WordPress & ExpressionEngine. See more of my work, and then hire me.

Recent Work

  • 4th District IBEW Health Fund
  • Employers Council on Flexible Compensation
  • Monica Davis
  • The National Christmas Tree
  • Matrix Group International
  • The MatriX Files
  • Wireless Career
  • George Washington Wired
  • Direct Selling 411
  • Makeup Bizz
  • InstallNET
  • National Park Foundation
See More of My Work

Asides