Latest tutorial: Making a Movieclip face another Movieclip or point on the stage | Ask Tutorial5!
 

Input form text switch using JavaScript

(12 votes)
Written by DanielRo   
In this tutorial we are presenting a very simple and efficient method of providing extra information in form text fields using simple JavaScript.

When building forms you will always find a need to provide more and more information and guidelines regarding the type and form of data you want users to submit by using the bare minimum of code and ease of mind.

By using JavaScripts onFocus and onBlur event handlers one can provide text in text fields that automatically disappears when the user is editing that field.

Input form text switch using JavaScript example

Here is the actual code snippet:

<input type="text" name="searchbox" value="Enter search phrase" onfocus="if (this.value == 'Enter search phrase') {this.value = '';}" onblur="if (this.value == '') {this.value = 'Enter search phrase';}" />
<input type="button" value="Go" />


This is typical code sentence for a input type text field except for the extra JavaScript.

value="Enter search phrase"
This is the place were the default input text is declare, "Enter search phrase" will be auto typed into the input text field.

onfocus="if (this.value == 'Enter search phrase') {this.value = '';}"
When the user clicks on the text field the script checks to see if the value of the text field is "Enter search phrase". If the values match value="Enter search phrase" and (this.value == 'Enter search phrase') then the script resets the text field default value to nothing {this.value = '';}.

onblur="if (this.value == '') {this.value = 'Enter search phrase';}"
When the user clicks outside of the text field the script checks to see if the default value has been modified (if the user entered information). If the user did not enter any info and the text field is blank, then the script resets the default text field value to Enter search phrase {this.value = 'Enter search phrase';}.

To get this working on your forms all you need to do is copy this code and replace the three instances of Enter search phrase with whatever you want your text fields to display.


Subscribe now via RSS feed and get all the new tutorials

written by Johan , March 07, 2008

Thanks!! :D

I've searched in 2 hours for this, and finally found it. :)

- Johan
written by Lark , March 11, 2009

Yes! I've also been looking for this as well... and thank you for the explanation. I am trying to learn javascript so that is very helpful (as opposed to most sites where they just throw the code at you).

Muchos Gracias!

- Lark
written by ghd , July 26, 2010

Thanks!! :D

I've searched in 2 hours for this, and finally found it. :)

- Johan

Do you need more help? Ask now!
 

busy
Last Updated ( Sunday, 21 October 2007 )