Using Javascript for Commenting in Inputs

You can use Javascript to build inline comments for your input fields.  This is a great way to denote required fields and pre-populate data.  If you’re using this script to show comments on required fields, I would suggest combining it with some sort of server or client side validation script – or both.  The code is an example SIMILAR to the way WordPress’s comments form looks.  Some day I will build a widget for this.

The Code

<h4>Leave a Reply</h4>
<form action="action.php" method="post" id="commentform">
  <div class="inputs">
    <input type="text" name="author" id="author"
      onClick="removeTextCheck(this,'(Required)');"
      onBlur="addTextCheck(this,'(Required)');"
      value="(Required)" />
    <input type="text" name="email" id="email"
      onClick="removeTextCheck(this,'(Required)');"
      onBlur="addTextCheck(this,'(Required)');"
      value="(Required)" />
    <input type="text" name="url" id="url" value="" />
  </div>
  <textarea name="comment" id="comment"
    onClick="removeTextCheck(this,'(Your Message)');"
    onBlur="addTextCheck(this,'(Your Message)');">(Your Message)</textarea>
</form>
<script type="text/javascript">
  function removeTextCheck(element,initialValue) {
    if(element.value == initialValue) element.value = "";
  }

  function addTextCheck(element,initialValue) {
    if(element.value == "") element.value = initialValue;
  }
</script>

Explanation

This code is actually pretty simple.  For each element that you wish to do an inline comment for, you’ll need an “onClick” even and an “onBlur” event.  For the “onClick” event you’ll create a function called “removeTextCheck” and call it in each input or text area that you’d like to leave an inline comment for.  For the “onBlur” event, you’ll create a function called “addTextCheck” and call it in each input or text area that you’d like to leave an inline comment for.

Both functions have two arguments: “element” and “initialValue” which have pretty much the same definition in both functions.  The “element” argument is the element in which you are placing the inline comment.  You will always use the “this” variable when calling this function inline.  If you call it from somewhere else in your page you may want to use something like “getElementById” or something similar.  The second argument “initialValue” will be the value that you wish to check against for adding/removing the text.  In my code above, that was either the “(Required)” values or the “(Your Message)” value.  You will want to make sure that this argument matches the value attribute of either your input or textarea.

Did this make sense to you?  Let me know!

Oh, and the code above can be copied and pasted as is into a blank text document to creat a working page.