Use jQuery to Enhance your WordPress Comment Form

I have already completed a couple of tutorials on forms and jQuery (Ajax Forms with jQuery and Flexible and Semantic Forms with a Little jQuery), but I wanted to show another example of using a simple jQuery script to enhance functionality. This example will be about the comment form on a WordPress powered site.

WordPress Validation ScreenshotDepending upon your configuration, WordPress will validate the comment form for required fields. In my configuration, I want to make sure that users fill in their name and email address If you submit my comment form without those, WordPress will perform server side validation.

But, do you really want users to see this error page? Wouldn’t it be so much better if we used to JavaScript to validate on the client side so that they never have to leave the form?

I think so. Before we get started, I created a sample of the WordPress comment form.

See Example Page

Creating the Markup

I have tweaked my markup somewhat from the default WordPress comment form, so you will need to make changes to account for your markup. Here is the markup for my form:

<form action="#" method="post" id="commentform">
 <
class="required">* Denotes Required Field</p>
 <
ol class="forms">
  <
li>
   <
label for="author">Name <span class="required">*</span></label>
   <
input type="text" class="requiredField" name="author" id="author" size="22" />
  </
li>
  <
li>
   <
label for="email">E-Mail <span class="required">*</span></label>
   <
input type="text"  class="requiredField" name="email" id="email" size="22" />
  </
li>
  <
li>
   <
label for="url">Website</label>
   <
input type="text" name="url" id="url" size="22" />
  </
li>
  <
li class="textarea">
   <
label for="comment">Comments <span class="required">*</span></label>
   <
textarea  class="requiredField" name="comment" id="comment" cols="100%" rows="10"></textarea>
  </
li>
  <
li class="subscribe-to-comments">
   <
input type="checkbox" name="subscribe" id="subscribe" value="subscribe"  />
   <
label for="subscribe">Notify me of followup comments via e-mail</label>
  </
li>
  <
li class="buttons">
   <
button type="submit" name="submit" id="submit">Add Comment &raquo;</button>
  </
li>
 </
ol>
</
form

I don’t think there is much that I need to discuss about that markup; it is pretty standard. The only thing to mention is the class name of requiredField on the form fields that I want to be required. Note: I also removed the action on the form so that the sample form cannot really be submitted to the database.

The jQuery

I of course am going to show this example using jQuery, but you could create something comparable with any other JavaScript library or just with some plain old JavaScript.

Once the document is loaded, let’s start by adding a function for when the comment form is submitted:

$(document).ready(function() {
 
$('form#commentform').submit(function() {
 
&hellip;
 
});
}); 

Next, we want to remove any errors if they are showing, and create a flag that will let us know if an error has occured:

$(document).ready(function() {
 
$('form#commentform').submit(function() {
  
<strong>$('form#commentform .error').remove();
  var 
hasError false;</strong>
  &
hellip;
 
});
}); 

Ok, here is where we really start to do some coding. I want to take each form field that has a class of requiredField, check to see if it is empty, copy the name of the label (and remove the required asterisk), traverse to the parent list item, and append the error message. Here is where we will also set the hasError flag so that we know an error has occurred:

$(document).ready(function() {
 
$('form#commentform').submit(function() {
  
$('form#commentform .error').remove();
  var 
hasError false;
  <
strong>$('.requiredField').each(function() {
   
if(jQuery.trim($(this).val()) == ''{
    
var labelText = $(this).prev('label').text().replace(' *','');
    $(
this).parent().append('<span class="error">'+labelText+' is a required field.</span>');
    
hasError true;
   
}
  }
);</strong>
  &
hellip;
 
});
}); 

Finally, you want to check the hasError variable to determine whether or not you should submit the form to the server:

$(document).ready(function() {
 
$('form#commentform').submit(function() {
  
$('form#commentform .error').remove();
  var 
hasError false;
  $(
'.requiredField').each(function() {
   
if(jQuery.trim($(this).val()) == ''{
    
var labelText = $(this).prev('label').text().replace(' *','');
    $(
this).parent().append('<span class="error">'+labelText+' is a required field.</span>');
    
hasError true;
   
}
  }
);
  <
strong>if(hasError{
   
return false;
  
}</strong>
 
});
}); 

Note: The end of the script is slightly different on the example form because I did not want to actually submit the form.

Conclusion

Just another simple example of how we can improve the user experience by using jQuery. Like usual, there are jQuery plugins out there that can do the same thing, but I think it is important to understand how to do things yourself. Plus, that is only 17 lines of JavaScript compared to much, much more for a plugin.

Anyone have any ideas on how to improve the script?

42 Comments

aNiteo2k

01.13.2009

Look’s good.

You can add a method to validate emails and if the email isn’t a good email (thisisnotgodmail@) don’t submit the form.

Good Job ;)

Nate

01.15.2009

Good stuff, as always, my tutorial-writing friend.

I’m pretty tempted to tweak my next comments field implementation so that instead of just adding error messages to required fields, it removes all the fields that have been completed satisfactorily.  I think it might feel really intuitive: instead of, “Whoa, buddy!  Back on up,” the message is more, “Oops!  Couple things I still need from you.”  Anyway, if I get a chance I’ll whip it up and point you toward it.

Trevor

01.15.2009

@Nate-
Ohh, that sounds interesting. Sounds very 37 Signals-like. Definitely let me know when you’ve got something to show.

Use jQuery to Enhance your WordPress Comment Form

01.27.2009

[...] View original post here: Use jQuery to Enhance your WordPress Comment Form | Trevor Davis [...]

Best of the Web: January - NETTUTS

02.04.2009

[...] Visit Article [...]

Geek Week - CSS, jQuery,Wordpress, PHP, XHTML, Web

02.05.2009

[...] Use jQuery to Enhance your WordPress Comment Form [...]

Nency

02.06.2009

yes…please show something.

Frank

02.10.2009

Great script!
Please, can you add to clear the error message, when the klick often and has more error-messages?

Trevor

02.10.2009

@Frank-
I’m not sure what you mean by this:

Please, can you add to clear the error message, when the klick often and has more error-messages?

Frank

02.10.2009

When you click the submit button again, then add the script the span again after the labels.
The output on error-message is very often on the form.

Sorry, i hope you understand my bad english.

Trevor

02.10.2009

@Frank-

So are you saying, you submit the form, and the error messages display. Then, you submit the form again without filling anything in, and the error messages are still there? This is on purpose since there are still errors on the form.

When the form is submitted, it clears all of the error messages, and adds new ones:

$('form#commentform .error').remove(); 

Frank

02.10.2009

@Trevor: sorry, now i have seen my bug and this line. Thanks a lot

You are now listed on FAQPAL

02.11.2009

Use jQuery to Enhance your WordPress Comment Form…

A methos to keep losing your commentators to error pages using jQuery to keep them at the comment form….

M.A.Yoosuf

02.13.2009

its pretty awsome

Angellaa

02.23.2009

Hmm, very cognitive post.
Is this theme good unough for the Digg?

Kretzschmar

02.24.2009

Thanks for this. Already added it to my theme. Wonderful.

شات

02.25.2009

Nice

Even i saw same article else where i think

Any way its v.Good

Montana Flynn

04.21.2009

Having trouble adding it to my blog.

Trevor

04.21.2009

@Montana Flynn-
What kind of problems are you having?

Montana Flynn

04.21.2009

When I tried to do this my jquery s3slider stopped working and the validation didn’t work.  I set up all the right class’s and div’s.  Here is my current code (un-updated with your script)

<input type="text" name="author" class="comment-input" id="author" value="" size="27" tabindex="1" onclick="clickclear(this, '')" onblur="clickrecall(this,'')" /> Name (Required)

<
input type="text" name="email" class="comment-input" id="email" value="" size="27" tabindex="2" onclick="clickclear(this, '')" onblur="clickrecall(this,'')" /> Email (Required)

<
input type="text" name="url" class="comment-input" id="url" value="" onblur="if(this.value.length == 4) this.value='http://';" onclick="if(this.value == '') this.value='http://';" size="27" tabindex="3" /> Website (Optional)
 
<
input type="hidden" name="comment_post_ID" value="" /> 

Trevor

04.21.2009

@Montana Flynn-
I see an error in Firebug when I visit your website:

element[0] is undefined
http://blog.complimedia.com/wp-content/themes/rocksolid/js/s3Slider.js
Line 23

Montana Flynn

04.21.2009

How odd, I don’t know why it would be undefined, it is just a template javascipt file.  It is declared type=“text/javascript”.  Here is the s3Slider.js as well as another js for comparison.

<!--For s3Scroller-->
<
script type="text/javascript" src="/js/s3Slider.js"
<!--
End of s3Scroller-->
<!--For 
Smooth Scroll-->
<
script type="text/javascript" src="/js/smooth.pack.js">
<!--
End of For Smooth Scroll--> 

And I also thought of something, wouldn’t it be great to let commenters sign up for an account from the comment form? A check box “Sign up with the blog so you dont have to do that again” could go anywhere in your comment.php? Possible?

Trevor

04.21.2009

@Montana Flynn-
You should probably contact the developer of the slider plugin to get help on why it is not working.

It sure sounds possible to have people create an account as they fill out the comment form. There may already be a plugin for it.

ev eÅŸya depolama

05.21.2009

What kind of problems are you having?

Use jQuery to Enhance your WordPress Comment Form

05.26.2009

[...] Use jQuery to Enhance your WordPress Comment Form Trevor Davis   Posted by root 19 hours ago (http://trevordavis.net)      This example will be about the comment form on a wordpress powered site wordpress validation screenshot depending upon your configuration wordpress will     Discuss   |  Bury |   News | use jquery to enhance your wordpress comment form trevor davis [...]

Use jQuery to Enhance your WordPress Comment Form

05.29.2009

[...] Use jQuery to Enhance your WordPress Comment Form Trevor Davis   Posted by root 6 hours ago (http://trevordavis.net)      This example will be about the comment form on a wordpress powered site links are the most important part of the web make them stand out     Discuss   |  Bury |   News | use jquery to enhance your wordpress comment form trevor davis [...]

Use jQuery to Enhance your WordPress Comment Form

06.01.2009

[...] Use jQuery to Enhance your WordPress Comment Form Trevor Davis   Posted by root 2 hours 59 minutes ago (http://trevordavis.net)      This example will be about the comment form on a wordpress powered site wordpress validation screenshot depending upon your configuration wordpress will     Discuss   |  Bury |   News | Use jQuery to Enhance your WordPress Comment Form Trevor Davis [...]

Use jQuery to Enhance your WordPress Comment Form

06.01.2009

[...] Use jQuery to Enhance your WordPress Comment Form Trevor Davis   Posted by root 19 minutes ago (http://trevordavis.net)      This example will be about the comment form on a wordpress powered site wordpress validation screenshot depending upon your configuration wordpress will     Discuss   |  Bury |   News | Use jQuery to Enhance your WordPress Comment Form Trevor Davis [...]

Marc

06.12.2009

Hey, I got this thing ‘working’ with relative ease. Great tutorial and thanks for having an example page! Much easier to dig through the code setup using that.

That said, I do have one oddity with this thing.

As a logged in user, I did a test leaving the comment form blank and clicking submit. It gives me the error message as I expected, but everytime I click the submit button (without filling in the form) it adds another error message. So I clicked it a dozen times, theres a long line of “this is a required field” messages…

Where did I go wrong?

Trevor

06.12.2009

@Marc-
Excellent, glad you found the tutorial useful.

This line:

$('form#commentform .error').remove(); 

is what removes the error messages before re-running the validation.

Marc

06.12.2009

Well…I have that line in there, just as it is from your last (fully compiled) code example… why isn’t it removing before revalidatig?

Trevor

06.12.2009

@Marc-
Can you provide a link to the page?

Trevor

06.12.2009

@Marc-
It looks like your error messages have a class of contactform-error instead of just error, so you will have to account for that in the code.

Marc

06.12.2009

Oh wierd! It’s just a simple class (just changes the font color). I didn’t see that it was tied into the code above. I’m a dolt.

Thanks again for your quick responses! Slow day at hte office. hehe

Page bookmarked, I’ll be back!

user

06.19.2009

cool, exactly what i was seeking for, thanks

Lin and Jirsa photography

08.14.2009

Thanks for the information.  I’m trying to rework my blog now and this is very helpful!

Sample Forms

01.07.2010

Thanks for the information it is very helpful.

Vidanjör

02.05.2010

its pretty awsome

alex

04.19.2010

pretty nice :)
——-

miniMAC

07.17.2010

Thanks!

sample forms

07.30.2010

Superb! awesome.

What do you have to say?