Blogs at Gustavus / Web Services / Text input example text with jQuery
 

Text input example text with jQuery

 
 

Monday, June 23rd, 2008 by Joe Lencioni

When filling out a form on the web, it isn’t always crystal clear what you are supposed to type into every text input field. Since a confusing form is a form that is less likely to be completed, it is critical to provide help wherever important.

In these cases, it can be very helpful to have some example text that demonstrates the type of input that is expected. One compact implementation of this is to have faded example text in blank text inputs that disappears when your cursor focuses on them.

This trick can be elegantly accomplished with a little simple jQuery and the title attribute on the input field.

The JavaScript

function switchText()
{
	if ($(this).val() == $(this).attr('title'))
		$(this).val('').removeClass('exampleText');
	else if ($.trim($(this).val()) == '')
		$(this).addClass('exampleText').val($(this).attr('title'));
}

$('input[type=text][title!=""]').each(function() {
	if ($.trim($(this).val()) == '') $(this).val($(this).attr('title'));
	if ($(this).val() == $(this).attr('title')) $(this).addClass('exampleText');
}).focus(switchText).blur(switchText);

$('form').submit(function() {
	$(this).find('input[type=text][title!=""]').each(function() {
		if ($(this).val() == $(this).attr('title')) $(this).val('');
	});
});

The CSS

input.exampleText {
  color: #aaa;
}

The XHTML

<input type="text" name="example" title="e.g. Example text" />

Demo

One Comment

  1. [...] a larger image, but it’s damn useful. I hate that people tagged this with AJAX because IT ISN’T.Text input example text with jQuery - Web Services - Gustavus Adolphus College 20 hours agoA simple jQuery trick to put a gray-text value in an input field that disappears when [...]

Leave a Reply

 
 
Rate this:
Gustavus Adolphus College 800 West College Avenue
Saint Peter, MN 56082 USA
WORK (PREFERRED) 507-933-8000
Contact Us
Employment
Privacy Policy
 
© Copyright 2008, Gustavus Adolphus College, All Rights Reserved