Jan 13, 2009

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">
 <p 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?

Categories