Auto Clear and Restore Form Elements
Post #195 categorized as Function, last updated on Nov 4, 2007
Tagged with elements, forms, javascript, php, tips, tricks
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>
Share this..
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
#1 — August Klotz
Thank you for this post.