Tuesday, July 10, 2012

Automatically Clear Default Form Values

Many text input fields include descriptive text to help the user understand what they should type. With a very simple one line script, you can automatically clear the value and be ready for the user's input. For example, click on the text boxes below:

Top of Form

E-Mail:
Search:

Bottom of Form

Adding this to your form is extremely simple. We created a generic function, clearDefault() that can be used on any text input box:

function clearDefault(el) {

if (el.defaultValue==el.value) el.value = ""

}

Next, you need to call this script from the onfocus event of your input text box:

E-Mail:

VALUE="E-Mail Address"

ONFOCUS="clearDefault(this)">

Search:

VALUE="Search Text"

ONFOCUS="clearDefault(this)">

That's it! This works because initial value of the value attribute is assigned to the defaultValue property in JavaScript. When an input element receives the focus, we check if the defaultValue is the same as the current value. If they are equal, the text box is cleared before the user starts typing.

This technique can be further improved with dynamic styles in Internet Explorer by also using a different color for the default value. For example:

Top of Form

E-Mail:
Search:

Bottom of Form

In Internet Explorer 4.0 or later the default value in the e-mail field is red and the default value in the search field is italicized. In all browsers (except Navigator 4.0), the text is displayed unchanged. Netscape Navigator recognizes a few CSS attributes on the input element as well as misinterprets others (eg., text-align: center centers the entire line of text). When Netscape recognizes the CSS attribute, it cannot be dynamically changed. This happens in the search field above where the text stays italicized.

For this example, we used an enhance version of the clearDefault function:

E-Mail:

STYLE="color: red"

TYPE=text

VALUE="E-Mail Address"

STYLE="color: red"

ONFOCUS="clearDefaultandCSS(this)">

Search:

TYPE=text

VALUE="Search Text"

STYLE="font-style: italic"

ONFOCUS="clearDefaultandCSS(this)">

No comments:

Post a Comment

masukkan nama anda

Popular Posts