Fall Sale! Code FALL2024 takes 25% OFF our Pro Plugins & Books »
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 = Designer. Developer. Producer. Writer. Editor. Etc.
Digging Into WordPress: Take your WordPress skills to the next level.

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

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

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

  2. Oh my, shame on me, I missed the link. Here’s the correct one (404 link removed 2014/05/04). 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

  3. Perishable 2008/07/22 1:20 pm

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

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

  5. Perishable 2008/07/22 2:12 pm

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

  6. Perishable 2008/07/22 2:39 pm

    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! ;)

  7. Perishable 2008/07/22 2:40 pm

    Thanks for hijacking the comments, btw :)

  8. “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!

  9. 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!

  10. Jeff Starr 2008/09/01 9:13 am

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

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

  12. Jeff Starr 2008/10/21 4:11 pm

    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! ;)

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 »
Banhammer: Protect your WordPress site against threats.
Thoughts
I disabled AI in Google search results. It was making me lazy.
Went out walking today and soaked up some sunshine. It felt good.
I have an original box/packaging for 2010 iMac if anyone wants it free let me know.
Always ask AI to cite its sources. Also: “The Web” is not a valid answer.
All free plugins updated and ready for WP 6.6 dropping next week. Pro plugin updates in the works also complete :)
99% of video thumbnail/previews are pure cringe. Goofy faces = Clickbait.
RIP ICQ
Newsletter
Get news, updates, deals & tips via email.
Email kept private. Easy unsubscribe anytime.