Clearing or Highlighting Default Text

You often want to place a message into a text field that tells your visitor what they need to type into the field. You want the instructions to be there until they get to the field and then be replaced by whatever your visitor types in. Well here's a text box that does that.

All you need to do is to include the following script into the <head> section of your page:

function cl(t){if (t.defaultValue==t.value) t.value = '';}

The script gets called when the field gets the focus. For example the above text box is defined like this:

<input type="text" value="type something here" onfocus="cl(this);" />

If you have more than one text field on the form where you want this to occur, just include the same onfocus code in each and the text in the appropriate field will disappear when that field gets the focus (provided that the field still contains its original value, if your visitor returns to a field they have already changed then the field will not be cleared).

Of course you may not actually want to clear the default text, you might just want to highlight it so that it can be easily replaced (by typing a replacement value) but can be kept if your visitor actually wants to use the default value (by pressing an arrow key). This is even easier to do. If you are tabbing through the fields this happens automatically, all we have to do is to set things up so that it also happens when you select the field with the mouse. Here's an example:

In this instance we don't even need a separate function. The entire necessary code can be included in the field definition like this:

<input type="text" value="default value" onfocus=";" />

Both of these pieces of code will work with Internet Explorer 4+, Netscape 4+ and Opera 6+.


This article written by Stephen Chapman, Felgall Pty Ltd.

go to top

FaceBook Follow
Twitter Follow