How to Correctly Remove Default Values from Form Fields on Focus with Javascript

Lets consider that I am on a blog and trying to comment, the default value for the comment textarea is “Comments”, I focus (click) on the comment textarea and the default value removes itself (timesaver) then I type in few words and goes to google to search for a link that I want to add to the comment. I successfully find the link and focus on the textarea again when I notice that my comments was removed and I had to type it from scratch.

That is wrong and frusturating. It should only remove the default value from the form fields on focus not just any value.

With the help of jQuery, it is very easy to ONLY clear the default values from the form fields.

When the document is ready, we’ll build an array of “fieldname” = “default value”.  When there is focus on the form fields, we’ll match the default value from the array with the focused form field value. On match, it’ll remove the default value else it’ll not remove the default value.

Here’s my code which I use on my client’s blog.

jQuery(document).ready(function() {
  var default_values = {};
  jQuery('input, textarea').each(function(i) {
    var index = jQuery(this).attr('name');
    var value = jQuery(this).val();
    default_values[index] = value;
  });

  jQuery('input, textarea').focus(function() {
    if(jQuery(this).val() === default_values[jQuery(this).attr('name')]) {
      jQuery(this).val('');
    };
  })
});

One Response to “How to Correctly Remove Default Values from Form Fields on Focus with Javascript”

  1. Muhammad Abbas August 14th, 2008

    nice post, i am looking for something similar to what your post is about. Still its useful, thanks.

Leave a Reply