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" />
Leave a Reply