Self-labeling text entry INPUT boxes using Prototype JS

Like previous code snippets, this one is mostly all code and no explanation.

A brief primer: you’ve often seen self-labeling input boxes, the ones that display a label inside in gray text, and when you click replaces with an empty input element using Javascript. This is a simple class to help you achieve that effect:

SelfLabelingBox = {
	initialize: function(box_id, message) {
		this.setup_behavior(box_id, message);
	},

	setup_behavior: function(box_id, message) {
		box_id = $(box_id);
		if(box_id) {
			if(box_id.value == '') {
				box_id.value = message;
				box_id.addClassName('inactive');
			}
			Event.observe(box_id, 'focus', function() {
				if(box_id.value == message) {
					box_id.value = '';
					box_id.removeClassName('inactive');
				}
			});
			Event.observe(box_id, 'blur', function() {
				if(box_id.value == '') {
					box_id.addClassName('inactive');
					box_id.value = message;
				}
			});
		}
	}
};

SetupDefaultInputs = {
	initialize: function() {
		Event.observe(document, 'dom:loaded', this.setup_default_inputs);
	},

	setup_default_inputs: function() {
		SelfLabelingBox.initialize('search_text', 'Search');
	}
};

Until next time!

2 Replies to “Self-labeling text entry INPUT boxes using Prototype JS”

  1. I found your code and modified it to make it more ‘prototype-y’. Here’s what i came up with:

    Element.addMethods('input', {
      addAutoLabel: function(element, message){
        element = $(element);
        if(element) {
          if(element.value == '' || element.value == message) {
            element.value = message;
            element.addClassName('inactive');
          }
          Event.observe(element, 'focus', function() {
            if(element.value == message) {
              element.value = '';
              element.removeClassName('inactive');
            }
          });
          Event.observe(element, 'blur', function() {
            if(element.value == '' || element.value == message) {
              element.addClassName('inactive');
              element.value = message;
            }
          });
        }
      }
    });
    Array.prototype.addAutoLabel = function(message) {
        this.each(function(e){e.addAutoLabel(message);})
    }
    

    then to add it to a field (or fields) you invoke:

    $('element').addAutoLabel('automatic label');
    

    or

    $$('input.someclass').addAutoLabel('automatic label');
    

    Like

Leave a Comment

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s