Form Default Ghosting

Form Default Ghosting









I Heart AWeber.com

Do you love AWeber, too?

Have you seen web forms with example data in the form elements, but when you go to an element, the example magically disappears so you can type something in? Then, if you leave the field blank and move away from it, the example data magically reappears?

There's nothing magic going on there. It can be done easily with a little Javascript. Pure HTML cannot dynamically change data fields like that, it takes an active language running in the user's browser - like Javascript.

Plan The Behavior You Want

It's very easy to do this yourself. Let's think about what we really want to happen.

  1. a text field should start out containing the example string;
  2. when the user clicks (or tabs) onto the field (called Focus), if the example string is still in there, complete empty the field;
  3. when the user clicks (or tabs) away from the field (called Blur), if the field is still empty, set it back to the example string.

Example

Suppose you have a Date field, and you want to show people that the syntax they should enter is 2-digit Month, 2-digit Day, and 2-digit Year, like this: MM/DD/YY

Your plain HTML code might look like this:

<input name="startdate" value="MM/DD/YY">

Add The Magic Javascript

We change the HTML to look like this:

<input name="startdate" value="MM/DD/YY"
	onfocus="cleardate(this)" onblur="resetdate(this)">

Now we just need the two Javascript functions:

<script type="text/javascript">
<!--
function cleardate(item) {
	if (item.value == "MM/DD/YY")
		item.value = "";
}
function resetdate(item) {
	if (item.value == "")
		item.value = "MM/DD/YY";
}
// -->
</script>

We usually place this Javascript code in the <head> section of your HTML content. Yes, it could also go in the <body> section, but it's better if functions like this live in the <head> section to make sure they're defined before being used.

Give It A Try!

Try this out - click in a field, then click away. Try entering a value in a field, and clicking away. Try erasing the value and clicking away. The usual keys work too - the TAB key moves between fields, shift-TAB to move backwards thru the fields.


Start Date:
End Date:
(no Submit button, just an example)

Platforms Supported

This should work on every web browser out there which has Javascript. I tested it on MSIE 6.0, Firefox 2.0, and Opera 9.0; worked great every time.



Bookmark and Share


Don't miss the latest web tips and tricks!
Subscribe to our low-volume mailing list:

Privacy Policy

See other tricks:  Web | Unix | Perl | SQL | General


Sample Sites | Customers | Our Team | Contact Us | Tips and Tricks | Tools | Our Network | Home

Copyright © 2006 Fastech Learning LLC, all rights reserved.
Phone toll free 1-866-464-6688, Phoenix Metro area 480-895-6688
Problem with this web site? please let us know