Smart empty text field automatically

UPDATE: This code needs some work still!

I think everyone has seen a form on a web page that has text fields that automatically empty when they receive focus. I’ve added this functionality to countless fields over the years and the behaviour I used to to this has evolved more and more. Using Prototype and the following script you can have fields intelligently empty themselves.

function clear_field(el, handle_blur) {
  $(el).value_modified = false;
 
  $(el).onfocus = function() {
    if ($(el).value == $(el).defaultValue && $(el).value_modified == false) {
      $(el).value = '';
      $(el).value_modified = true;
    };
  }
  if (handle_blur !== false) {
    $(el).onblur = function() {
      if ($(el).value == '') {
        $(el).value = $(el).defaultValue;
      };
    }
  };
}
 
window.onload = function() {
   clear_field($("login"));
   clear_field($("password", false));
}

The “clear_field” function handles focus and can handle blur events. When a field receives focus for the first time the “value_modified” boolean variable is set to true and the value of the field is set to an empty string. Subsequent focus events will no longer empty the field as we do not want to interfere with the user’s interaction with our field.

If we supply a “false” argument after our element the blur event will not be applied. If this is the case the field will never be repopulated. Handy for password fields, as is indicated in the example above.

If the blur event is applied the field will be repopulated with it’s defaultValue if the field is empty when it loses focus.

I’ve uploaded a demonstration of the use of this code. You can find it at http://static.jamesconroyfinn.com/clear_field/.

Leave a Reply