Clearing the default value of text input with Javascript

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

Using plain old Javascript coded into the input tag

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.

    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.

Moving the Javascript out of the input tag

Instead of coding the onfocus (and onblur as suggested in one of the comments below) directly into the tag, they can be attached either using plain Javascript, or more easily with a 3rd party library like jQuery. I show how to do this with my "changing the default text value on focus with jQuery" post.

Related posts: