Edelman Technologies
http://blog.edelmantech.com/content/2007/03/clear_default_form_input_with_javascript.php
View Full Version

Clear Default Form Input with Javascript

By David Edelman on 03.02.07
Filed Under: Javascript

The search box at the top of the page defaults to "Search". However, when a user clicks on it, I want the box to become empty. Using Javascript, this is a piece of cake.

First, add the following to the head section of your page:

<script type="text/javascript">
function clearText(thefield){
 if (thefield.defaultValue==thefield.value)
 thefield.value = ""
} 
</script>

Good. Now you have a function called clearText() at your disposal. It simply checks to see if the current value of the field equals the default value. If it does, it will blank it out.

Here's the syntax for using this script on an input box:

<input type="text" value="Search" onFocus="clearText(this)" />

When you click on the box (i.e. onFocus), it will check if the box's currently value ("Search") is equal to the default value (still "Search") and make it empty.

This script is simpler and better than most of this variety. If you type something into the search box and use your browser's back arrow, the last thing you typed will remain in the box. The text in the box because it will no longer be equal to the default value. Many script simply empty the box every time you click on it. This can be annoying if you've created a long search phrase and only want to change a word or add quotation marks.