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.
Related Posts




















October 25, 2006 @ 9:39 am
Brrrrilliant!!
thanks, this is exactly what i wanted
[Reply]