Clear Input Field Value When Selected
fieldsOften when creating forms on a website it is helpful to place descriptive text with some of the form fields to help the user understand what they should type in the box. If this descriptive text is not cleared automatically when the user begins to type, sometimes this will hinder them more than it helps.
Using a simple JavaScript function you can automatically clear the example values from the input box when the user clicks into the field.
For an example of how this works, look at my search field to the right.
This technique can easily be used to clear the contents of any input box.
To use this effect, first you must create a generic ‘clearDefault()’ function:
function clearDefault(el) {
if (el.defaultValue==el.value) el.value = ""
}
Then call this function using the ‘onfocus’ value of your input box:
<input value="Your Comment" onfocus="clearDefault(this)" type="text">
This works because initial value of the value attribute is assigned to the defaultValue property in JavaScript. When the input element gets clicked into, or becomes the focus, the script checks to see if current value is the same as the default value. If they match up, the text box is cleared out.
This prevents the filed from becoming cleared again if the user wished to edit their input after clicking out of the filed.














October 25, 2006 @ 9:39 am
Brrrrilliant!!
thanks, this is exactly what i wanted
Reply
January 11, 2009 @ 6:10 am
Perfect! Thanks mate!
Reply
February 27, 2009 @ 5:50 am
Thank you
This little script solved a long boring problem, I’ve had.
The working script can now also be seen at my site.
You sure provided something of value.
Michael’s last blog post… It’s Not Safe
Reply
zacheos
You’re welcome
Reply
March 26, 2009 @ 1:45 am
How do I make the value return to the input field, when clicking somewhere else, if I didn’t enter any text(like this: http://buildinganonline.com/contact)?
Reply
June 24, 2009 @ 2:48 am
Thnks for this.
Reply
October 7, 2009 @ 10:23 pm
Thanks for this tip!
Bookmarked this page.
Reply
October 25, 2009 @ 5:00 pm
To back to default value if it is empty, you can add this function in “onblur”
function backDefault(el){
if (el.value==”") el.value = el.defaultValue
}
Reply