Clearing the default value of text input with JavascriptClearing the default value of text input with Javascript

Posted June 17th, 2008 in Javascript

Often in a web form you will put a default value into a text box which explains what the box is for and when the user clicks into the box clear the value. An example of this is a sidewide search box where you might want to put the instructions (e.g. "enter your keywords here") in the box instead of as a title for the text input. This post looks at how to clear the value only if it is set to the default value with Javascript.

The desired behaviour is when the user clicks or tabs into the text box it clears the value only if it is set to the default value, i.e. if they have since changed it from the default value, and click back into the box we don't want to change the value they have changed it to.

This is very simple, as shown in the example below.

<input
    type="text" 
    value="enter your keywords here" 
    onfocus="if(this.value == this.defaultValue) this.value = ''"
/>

The default value is "enter your keywords here", and when the text box gets focus (the onfocus="" part) it will clear the value if it is still the default.

This is done using the Javascript object "this" which is a reference to the current element, in this case the input tag. We compare the current value (this.value) with the default value (this.defaultValue) and if they are the same set the element's value to an empty string.