Spring Sale! Save 30% on all books w/ code: PLANET24
Web Dev + WordPress + Security

Unobtrusive JavaScript: Auto-Clear and Restore Multiple Form Inputs on Focus

In an effort to organize my pile of offline notes, I will be posting a number of quick, “to-the-point” tutorials on a number of useful topics. In this post, I share an excellent method for auto-clearing and restoring multiple form field inputs using a bit of unobtrusive JavaScript. This method was discovered at xy.wz.cz. There are two steps to this technique, which should take no longer than five minutes to implement.

Step 1: Prepare the Form

Begin by preparing your form as you would like it to function without JavaScript. For example, you may have a comment form that looks something like this:

<form>
	<fieldset>
		<label for="author">Name</label>
		<input type="text" name="author" id="author" value="Name" />
		
		<label for="email">Email</label>
		<input type="text" name="email" id="email" value="Email" />

		<label for="website">Website</label>
		<input type="text" name="url" id="url" value="Website" />

		<label for="comment">Comment</label>
		<textarea id="comment" name="comment"></textarea>

		<input id="submit" name="submit" type="submit" value="Submit" />
	</fieldset>
</form>

Make sure that each of the form inputs has a type value of text. That’s all we need to do to prepare the form. To summarize this first step, any form inputs with at least the following attributes will work just fine with the auto-clear/restore script:

<input type="text" value="Name" />
<input type="text" value="Email" />
<input type="text" value="Site" />

Step 2: Add the JavaScript

In a file named “autoclear.js” (or whatever), add the following slice of JavaScript:

function init(){
	var inp = document.getElementsByTagName('input');
	for(var i = 0; i < inp.length; i++) {
		if(inp[i].type == 'text') {
			inp[i].setAttribute('rel',inp[i].defaultValue)
			inp[i].onfocus = function() {
				if(this.value == this.getAttribute('rel')) {
					this.value = '';
				} else {
					return false;
				}
			}
			inp[i].onblur = function() {
				if(this.value == '') {
					this.value = this.getAttribute('rel');
				} else {
					return false;
				}
			}
			inp[i].ondblclick = function() {
				this.value = this.getAttribute('rel')
			}
		}
	}
}
if(document.childNodes) {
	window.onload = init
}

And then call it from your (X)HTML document (the one containing the form):

<script src="autoclear.js" type="text/javascript"></script>

Alternately, the script may be placed in the head section of the (X)HTML document that includes the form. Also, to improve performance, you may want to compress the script using an online JavaScript compressor.

Once everything is in place, upload and check it out. Everything should work great, even in good ol’ IE 6! ;)

Styling Forms

For more help creating, styling and enhancing your (X)HTML forms, check out Chris Coyier’s excellent CSS-Tricks article Tips For Creating Great Web Forms.

Autoclear Demo

To try a live example, check out the Autoclear & Restore Demo »

About the Author
Jeff Starr = Web Developer. Book Author. Secretly Important.
Blackhole Pro: Trap bad bots in a virtual black hole.

38 responses to “Unobtrusive JavaScript: Auto-Clear and Restore Multiple Form Inputs on Focus”

  1. Hi,

    I found your blog entry trough the almighty Google and although it totally fits my needs, I found one ‘problem’ with this approch; when you double click a field, it resets the data in the field to the default text.

    So if, for example, you enter ‘asdf’ into one of the fields and then double click that field, it will retun to ‘Your Name’ (talking about the Demo page now).

    My Javascript knowledge is verry _verry_ limited so I was wondering if you know a workaround for this? Besides not double clicking a field that is ;-)

    Tested on Firefox 3.0.5 and Safari 3.2.1 (mac).

  2. Hey mate, sorry but i ran the demo in IE6 and it doesn’t work. I have tried similar code on my own site and it does a similar thing to yours : works in fox but not in ie6.

    In ie6 if you hit refresh it holds on to the entered data, hit refresh about 5 times then it resets. i.e. it works after a few refreshes. any idea why?

  3. Jeff Starr 2009/03/01 9:14 am

    @Cj: The script still seems to work just fine on IE6 for me. Of course, I’m not sitting there refreshing the page over and over again either. I suppose you could break just about anything if you try hard enough, especially on IE6! :P

  4. Sorry i think i may have worded my statement incorrectly. you’re right – btw we have to use ie6 at work for some reason. go figure

  5. Adam Smith 2009/03/04 2:24 pm

    Awesome script!

    How can I edit it to work with BOTH inputs and textareas?

    Thanks,
    Adam

  6. Lewis Litanzios 2009/03/08 8:18 pm

    Good script, if a little heavier than I expected. I’m with Adam Smith here I’m afraid. Will look around for something better unless you can get back to me/us.

    Cheers

  7. Jeff Starr 2009/03/08 9:24 pm

    @Lewis: Have you tried this jQuery solution? (A jQuery Function to Auto-Fill Input Fields and Clear them on Click) (404 link removed 2012/07/26) It may provide you with something that will work or may be tweaked to work.. Requires jQuery but the script itself is much smaller.

  8. Jeff Starr 2009/03/08 8:34 pm

    @Lewis Litanzios: You’re “with Adam Smith” about what, exactly? Adam was asking about applying the technique to the <textarea>, which would require additional code. Of course, this would in turn make the script even “heavier” than it is already, so I guess I’m a little confused about your comment. I would love to see anyone make the code lighter (your concern) and enable additional functionality (Adam’s concern) at the same time.

  9. Lewis Litanzios 2009/03/08 8:45 pm

    Hey Jeff,

    Don’t get me wrong, I’m grateful for the script. I’ve had a look round for an alternative over the last 10mins, but there’s hardly any equivalents that are unobtrusive. I guess the weight of this script – simply for an input clear?! – just seemed a lot compared to the usual stuff I have been using involving obtrusive solutions. Apologies if I offended.

    Any help getting this to work for too?

    Thanks

  10. Jeff Starr 2009/03/08 8:56 pm

    Have you tried compressing the script? I am able to get it down to 491 bytes without even trying. Considering the fact that this script is 1) independent of any external JS library, and 2) completely unobtrusive, I think it’s a fine solution that works great even in IE6.

  11. Lewis Litanzios 2009/03/08 9:03 pm

    I’m more concerned about getting it working for and , and less about size, at this point in time. Any thoughts?

    I’ve tried duplicating the script, but with (‘textarea’), and changing up the variables etc but I think my JS arrangement is to blame – can’t get it working. Drop me an email if you like.

    Appreciate the help.

  12. Jeff Starr 2009/03/08 9:09 pm

    @Lewis Litanzios: Check your comments – I think WordPress may be gobbling certain parts of your sentences (the code maybe?).. To add a bit of code to this thread, wrap each word, phrase or line with <code> tags.

Comments are closed for this post. Something to add? Let me know.
Welcome
Perishable Press is operated by Jeff Starr, a professional web developer and book author with two decades of experience. Here you will find posts about web development, WordPress, security, and more »
USP Pro: Unlimited front-end forms for user-submitted posts and more.
Thoughts
I live right next door to the absolute loudest car in town. And the owner loves to drive it.
8G Firewall now out of beta testing, ready for use on production sites.
It's all about that ad revenue baby.
Note to self: encrypting 500 GB of data on my iMac takes around 8 hours.
Getting back into things after a bit of a break. Currently 7° F outside. Chillz.
2024 is going to make 2020 look like a vacation. Prepare accordingly.
First snow of the year :)
Newsletter
Get news, updates, deals & tips via email.
Email kept private. Easy unsubscribe anytime.