Enhanced Text Input Fields

Ever get annoyed when you encounter a text input field with a default value and are forced to clear the default text before you enter your own value?
Here's a small piece of code that I use to help solve the common UI annoyance.

Here's a sample of what you'll be creating:

First, you'll need to add the following code to your page. I recommend creating an external .js file and attaching it in the head area of your document.
 


function clearText(field){

	if (field.defaultValue == field.value) field.value = '';

	else if (field.value == '') field.value = field.defaultValue;

}

Next, you'll add the following input field anywhere within your HTML document.
 

<input type="text" value="Your default value goes here" onfocus="clearText(this)" onblur="clearText(this)" />

You can see in the code above that we've added a javascript function, "onfocus="clearText(this)" and onblur="clearText(this)", to the input element. Now, whenever a user clicks the field, it will call the above javascript function clearText(). The function checks the field, if the default value matches the current field value, it replaces the value with an empty string. The else if part of the function comes into play when the user clicks outside of the input field. It checks to see if the field value is empty, it replaces the empty string back to the default value.

You can probably easily modify this using Jquery to automatically call the function on each text field in your project rather than having to include the javascript function call on each text input manually. However, If you have a modest amount of text fields on your site, this could be the perfect solution!

0 Comments

Post new comment

The content of this field is kept private and will not be shown publicly.
  • Web page addresses and e-mail addresses turn into links automatically.
  • Lines and paragraphs break automatically.

More information about formatting options