Auto Clear and Restore Form Elements

by Jeff Starr on Tuesday, August 29, 2006 2 Responses

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>

About the author

[ Jeff Starr ]

Jeff Starr is a web developer, graphic designer and content producer with over 10 years of experience and a passion for quality and detail. Jeff is co-author of the book Digging into WordPress and strives to help people be the best they can be on the Web. + Follow Jeff on Twitter and subscribe to Perishable Press for quality web-design content delivered fresh.


2 Responses
[ Gravatar Icon ]

August Klotz#1

Thank you for this post.

[ Gravatar Icon ]

Perishable#2

Happy to help!

Comments are closed for this post

If you have or need further information, contact me.



Attention: Do NOT follow this link!