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
- Unobtrusive JavaScript: Auto-Clear and Restore Multiple Form Inputs on Focus
- Auto-Focus Form Elements with JavaScript
- Quick JavaScript Tip: Auto-Highlight Form Inputs and Textareas
- WordPress Search Function Notes
- Another Mystery Solved..
- Prevent JavaScript Elements from Breaking Page Layout when Following Yahoo Performance Tip #6: Place Scripts at the Bottom
- Slideshow Code for Dead Letter Art
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 »
Bookmark • Subscribe • Explore
« Optimize Convoluted Code via JavaScript • Up • XHTML Document Header Resource »
1 • October 3, 2006 at 5:31 am — August Klotz says:
Thank you for this post.