Unobtrusive JavaScript: Auto-Clear and Restore Multiple Form Inputs on Focus
by Jeff Starr on Tuesday, July 22, 2008 – 41 Responses
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.
Focused on clean code and quality content, Perishable Press is the online home of Jeff Starr, author, artist, designer, developer, and all-around swell guy. 





41 Responses
Add a comment
Louis – #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
inputelement (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
bodyenhances the performances (you suggest thehead).Perishable – #2
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 ;)
Louis – #3
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
Perishable – #4
@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.
Louis – #5
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.
Perishable – #6
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! ;)
Perishable – #7
Thanks for hijacking the comments, btw :)
Erika – #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!
John – #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!
Jeff Starr – #10
My pleasure, John — thanks for the feedback! :)
Patrick – #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.
Jeff Starr – #12
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 requirednameandtypeattributes in the form markup located in the PHP file. That’s really all there is to it.. don’t overthink it! ;)Marcel – #13
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).
Cj – #14
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?
Jeff Starr – #15
@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
Cj – #16
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
Adam Smith – #17
Awesome script!
How can I edit it to work with BOTH inputs and textareas?
Thanks,
Adam
Lewis Litanzios – #18
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
Jeff Starr – #19
@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.Lewis Litanzios – #20
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
Jeff Starr – #21
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.
Lewis Litanzios – #22
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.
Jeff Starr – #23
@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.Lewis Litanzios – #24
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.
Lewis Litanzios – #25
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.
Jeff Starr – #26
@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.
Lewis Litanzios – #27
Haha, Snook (http://twitter.com/snookca) just sent me to that very page! Cheers mate.
Best.
Jonathan Ellse – #28
Is this the same piece of code that highlights the search box in Quintessential when you hover over it? Or is that something different?
Jeff Starr – #29
@Lewis Litanzios: Great minds think alike! ;)
@Jonathan Ellse: That’s just a bit of CSS trickery. I use the
activeandhoverpseudo-classes to change the style on activation and hover, respectively.Dale – #30
You can make this work with textareas, in the following way.
http://pastie.org/558938
Jeff Starr – #31
Thanks Dale — I may be updating the post or even writing up a new article with this information. Cheers :)
SK – #32
Hi Jeff,
I’m brand new to Javascript and I have a question about your script. Are you storing the default value of the field in the “
rel” attribute for any particular reason? Is this just simpler than using a variable?I know I’m a year and a half late but thanks for the great post!
Jeff Starr – #33
Hi SK, you know, quite honestly I don’t remember why this script worked out the way it did. Using the
relis certainly cleaner than using a variable, so maybe that is indeed the reason..Mohamad – #34
Hey there, thank you for this script… I have a small question:
Is there anyway to change the colour of the default values? For example, in many similar scripts, the default values are usually in a lighter color than ones that are user input…
Many thanks for this,
Joe Sak – #35
Hey Jeff…
Thanks for posting my plugin to @lewis! I wanted to let you know I’ve since updated the plugin and am hosting it on github. I added password field support.
Check it out, thanks!
http://github.com/joemsak/jQuery-AutoFill
Joe Sak – #36
@Mohamad — my plugin has this option… see above
(@jeff — sorry for double post. I should have read more comments so I could consolidate my responses)
Jeff Starr – #37
Very nice, Joe — Thanks for the update!
Trackbacks / Pingbacks