Javascript: clear default text onClick – restore if nothing entered

Still on hiatus :) but wanted to post a little javascript (mainly for my future reference) I’ve used a few times in various applications.

One function will clear the “default” text in a field when the user clicks into it. The second function will replace the default text in the field if the field was left blank.

This goes inside the <head></head> tags:

<script type="text/javascript">
function clickclear(thisfield, defaulttext) {
if (thisfield.value == defaulttext) {
thisfield.value = "";

function clickrecall(thisfield, defaulttext) {
if (thisfield.value == "") {
thisfield.value = defaulttext;

Then you add the following onclick, onblur events to your field. (Shown in bold):

<input type="text" name="myfield" value="default text" onclick="clickclear(this, 'default text')" onblur="clickrecall(this,'default text')" />

Uses? a search field – your “default text” could give clues about what you can search for. ie “Enter keyword or item #”. Or it could display the format of the content you want from your user, ie. a date field with this as the default text “MM-DD-YYYY”.

Update 11/16/05 Updated script on the suggestion of Joan and Sunny.

Update 11/24/05 Here’s another neat way to do this without the “onclick” and “onblur” embedded in the input tag itself.



Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s