Jump Menu : Content | Explore | Comments | Search | Home | Sitemap | Contact | Login | Access.

Auto Clear and Restore Form Elements

Using a small bit of JavaScript, it is possible to auto-clear and restore form elements when users bring focus to them. Simply copy, paste, and modify the following code example to achieve an effect similar to this:

 
<form action="http://domain.com/" method="post">
   <p>
      <input value="Click here and this will disappear.." onfocus="if(this.value == 'Click here and this will disappear..') {this.value = '';}" onblur="if (this.value == '') {this.value = 'Click here and this will disappear..';}" type="text" size="77" />
   </p>
</form>

Update [January 2nd, 2007] » Here is another auto-clear JavaScript trick that cleans up the (X)HTML code but does not auto-restore the element. Simply place the first code block into the document head (or external JavaScript file), and then flesh out form elements in the second of block of code and place within the document body:

<script type="text/javascript">
<!--//--><![CDATA[//><!--
   function m(el) {
      if ( el.defaultValue == el.value ) el.value = "";
}
//--><!]]>
</script>
<form method="post" action="<?php echo $PHP_SELF; ?>">
 <p>
  <input type="text" name="target" value="This will disappear upon user focus.." onFocus="m(this)">
  <input type="submit" name="submit" value="Submit">
 </p>
</form>

Related articles

About this article

This is article #195, posted by Jeff Starr on Tuesday, August 29, 2006 @ 10:42am. Categorized as Function, and tagged with elements, forms, javascript, php, tips, tricks. Updated on November 04, 2007. Visited 16258 times. 2 Responses »

BookmarkSubscribeExplore

« Optimize Convoluted Code via JavaScript • Up • XHTML Document Header Resource »


2 Responses

1 • October 3, 2006 at 5:31 am — August Klotz says:

Thank you for this post.

2 • January 2, 2007 at 4:17 pm — Perishable says:

Happy to help!

[ Comments are closed for this post. ]


Set CSS to lite theme
Set CSS to dark theme