self clearing text input fields with javascript

I found that I use a lot of input fields which need to display a simple message to the user like “type the molecular structure of didehydro-dimethylether onium cation” — and when they focus the box it needs to clear, and when they blur the box it needs to go back to that message. Theres the sloppy way of doing it in the text box itself with the attribute callbacks “onfocus/blur” but thats annoying. I decided to make a simple extension to the HTMLInputElement instead like a good boy.

Here is the input extension to make a text field (actually, _any_ input, but you can add that logic yourself:) ) self clearing:

Requires Prototype Javascript Library!
I used v1.6 but I’m sure others will work fine.

// input_extensions.js

// extends HTMLInputElement to include a self-clearing method
// @author Rob Hurring
// @date 2008-04-23
// UPDATED: 12/02/08 -- thanks to Shawn for pointing out the IE flaw

var SelfClearingInput = Class.create();
SelfClearingInput.prototype = {
	initialize:function(element)
	{
		this.element = $(element);
		this.original_value = this.element.value
		Event.observe(this.element, 'focus', this.focus.bind(this));
		Event.observe(this.element, 'blur', this.blur.bind(this));
	},
	focus:function(e)
	{
		if(this.element.value == this.original_value)
			this.element.value = '';
	},
	blur:function(e)
	{
		if(this.element.value == '')
			this.element.value = this.original_value;
	}
};

when you want to use it, something like this can work:

// In your javascript file somewhere
document.observe("dom:loaded", function()
{
	new SelfClearingInput('ID_OF_INPUT_BOX');
});
For more info check out the project page at JavaScript Self Clearing Input @ GitHub


Comments

  1. Shawn August 20th

    Comment Arrow

    This doesn’t work in IE, due to the lack of support for HTMLInputElement.prototype. Do you have a workaround for this to make your code work in IE?


Add Yours

  • Author Avatar

    YOU


Comment Arrow



About Author

Rob Hurring

Ruby, Rails, PHP, bash... oh my!