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

Post #585 categorized as Function, last updated on Jul 23, 2008
Tagged with elements, forms, javascript, tips, tricks, tutorials

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) like this:

<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 Example

To see a working example of this technique, check out the autoclear & restore demo page.

Subscribe to Perishable Press


33 Responses

TopLeave a comment

[ Gravatar Icon ]

#1Louis

You may want to indicate that this is done in a much easier way on Safari, by simply adding a “placeholder” attribute to the input element (more here).

Proprietary, but yet very cool.

You may also want to note that YUICompressor does a better job when talking about JS compression, and also that placing the JS at the end of the body enhances the performances (you suggest the head).

[ Gravatar Icon ]

#2Perishable

Hi Louis, thanks for the info on Safari; too bad all browsers don’t provide such a feature. Btw, the link you provided needs an actual URL — the title doesn’t work! ;)

Good points on the optimal JavaScript placement. I discuss that issue in a previous article, yet for some reason mentioning it here escaped me.

As for YUICompressor, I have read supporting evidence about its excellent functionality, however, I chose to link to Dean’s compressor as a matter of personal preference. Hopefully, I will have the time to write an article discussing the different JavaScript compressors, but something tells me that I don’t need to worry about it ;)

[ Gravatar Icon ]

#3Louis

Oh my, shame on me, I missed the link. Here’s the correct one. Note that this link is not the best ressource I could find on the subject, but strangely, Google is quite silent on those keywords today.

As for the JavaScript compressors war, I’m definitely out of this one! I wrote on that subject very largely on my blog (in french, of course…) and I don’t see me doing the same deep analysis here, in english :/

That said, I can’t understand your preference for a compressor that is clearly inferior to Yahoo’s… oh sorry I meant “Dean’s compressor” :d

[ Gravatar Icon ]

#4Perishable

@Louis: previous link now fixed — thanks for the update (just don’t let it happen again! ;)

Without getting into the barbaric compressor wars, allow me to simply state that I would rather use Dean’s resources than Yahoo’s. It’s merely a matter of personal choice, sort of like preferring to shop at local markets rather than Wal*Mart. By no means do I advocate any compressor over another — it’s entirely up to the individual.

[ Gravatar Icon ]

#5Louis

Yes, but you are missing the whole point here: Julien Lecompte who writes the YUICompressor is french :p

No, seriously, I totally get the metaphor of Wal*Mart vs local store, but it’s not like Wal*mart was giving away his products. I mean, YUICompressor is a free, Open-Source tool.

They did test it on their huge network, but they are releasing this tool — among a lot more — for free. That does not sound like a dehumanized big company strategy, that sounds like a great gesture to me.

[ Gravatar Icon ]

#6Perishable

You are certainly free to justify it however you wish, so long as you don’t assume that your reasoning resonates with everyone else. Yahoo garners enough attention as it is; I would rather show support where it’s needed, appreciated, and deserved. Don’t worry, Louis, it’s okay if others think differently than you! ;)

[ Gravatar Icon ]

#7Perishable

Thanks for hijacking the comments, btw :)

[ Gravatar Icon ]

#8Erika

“It’s merely a matter of personal choice, sort of like preferring to shop at local markets rather than Wal*Mart.”

I KNEW I liked you for a reason! LOL!

[ Gravatar Icon ]

#9John

Appreciate the JS. I had a simple script that cleared the form, but it’s nice to be able to replace the text in case it’s not filled in. So I tossed a few words into Google and you page popped right up. Thanks!

[ Gravatar Icon ]

#10Jeff Starr

My pleasure, John — thanks for the feedback! :)

[ Gravatar Icon ]

#11Patrick

I have a newsletter subscription option on my website with an input box, only it is coded in php. I’m looking for a way to incorporate this javascript into my webpage, but I haven’t got a clue how to include javascript into php.

Is this possible and if so, how? Any help would be greatly appreciated.

[ Gravatar Icon ]

#12Jeff Starr

Hi Patrick, the tutorial should provide everything you need to get the script running.. make sure that you are linking to the JavaScript file from the <head> or footer section of your web page(s), and then add the required name and type attributes in the form markup located in the PHP file. That’s really all there is to it.. don’t overthink it! ;)

[ Gravatar Icon ]

#13Marcel

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).

[ Gravatar Icon ]

#14Cj

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?

[ Gravatar Icon ]

#15Jeff Starr

@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

[ Gravatar Icon ]

#16Cj

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

[ Gravatar Icon ]

#17Adam Smith

Awesome script!

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

Thanks,
Adam

[ Gravatar Icon ]

#18Lewis Litanzios

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

[ Gravatar Icon ]

#19Jeff Starr

@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.

[ Gravatar Icon ]

#20Lewis Litanzios

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

[ Gravatar Icon ]

#21Jeff Starr

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.

[ Gravatar Icon ]

#22Lewis Litanzios

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.

[ Gravatar Icon ]

#23Jeff Starr

@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.

[ Gravatar Icon ]

#24Lewis Litanzios

Sorry! My bad. I should have checked.

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.

[ Gravatar Icon ]

#25Lewis Litanzios

Sorry again, I’m messing your blog up here, hehe. Hopefully this works…

I’m more concerned about getting it working for <input> and <textarea>, 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.

[ Gravatar Icon ]

#26Jeff Starr

@Lewis: Have you tried this jQuery solution? It may provide you with something that will work or may be tweaked to work.. Requires jQuery but the script itself is much smaller.

[ Gravatar Icon ]

#27Lewis Litanzios

Haha, Snook (http://twitter.com/snookca) just sent me to that very page! Cheers mate.

Best.

[ Gravatar Icon ]

#28Jonathan Ellse

Is this the same piece of code that highlights the search box in Quintessential when you hover over it? Or is that something different?

[ Gravatar Icon ]

#29Jeff Starr

@Lewis Litanzios: Great minds think alike! ;)

@Jonathan Ellse: That’s just a bit of CSS trickery. I use the active and hover pseudo-classes to change the style on activation and hover, respectively.

Share your thoughts..

TopRead official comment policy

The rules are simple. Comment intelligently. Stay on-topic. Don’t spam! Suspected spam will be deleted. Use your real name or nickname, not a site name or business name. Using a site name or business name is a good way to get your link or comment removed. Certain comments are moderated; if your comment does not appear after several days, or if you wish to comment privately, contact me. Also, by posting a comment, you grant this site a perpetual license to reproduce your comment, name, and website URL. Lastly, you may use basic HTML markup, but please do not use <pre> tags. Instead, wrap your code with <code> tags. Use a new set of <code> tags for each code term or phrase, as well as for each individual line of code (i.e., multiple lines of code require multiple code tags). Please see the complete comment policy for more information.