Current Article
Industry Buzz
Social Networking
Featured Articles
Browse Content >
Back to Home

How to Add Suggestion Text to Your Input Fields

Geordie Konrad
Want to add an extra bit of professionalism to your web forms? This snippet allows you to provide default values for the input fields in your web form that disappear when the user focuses on that field. Add functionality while saving space!

Introduction

This is a really easy snippet to implement, it's going to feel like a freebie. We need only two reusable JavaScript functions. The first handles when a user focuses on the field, and the second handles when a user removes that focus.

Here are the two functions in full.

JavaScript Functions

 
function handleFocus(element)
{
    
    if (element.value == element.defaultValue) 
    {
        element.value = '';
    }
  
}

function handleBlur(element)
{

    if (element.value == '')
    {
        element.value = element.defaultValue;
    }

}

Here they are in plain english.

handleFocus: If the newly focused element contains the suggestion text, empty the field.
handleBlur: If the element which just lost focus is now empty, replace with the suggestion text.

Creating our Input Fields

Finally, we need to set up each input field with proper 'onfocus' and 'onblur' event handling. Make sure to add your suggestion text in the 'value' attribute!




Live Demo

Conclusion

While there isn't much to implementing this snippet, the functionality it adds is sure to turn heads. Usability is the name of the game, and this is a great step towards making that a reality for your users.

Please post any comments/suggestions below. Feedback is always appreciated, it lets us know how we are doing and how we can better serve the community!

Share Article

User Comments

Gravatar
Jay
5/14/2009
Thanks for this. Very simple. I was pleasantly surprised to find out this also works with the asp:TextBox tag (the initial text specified in the Text='' property). I registered the client script on PageLoad.
Gravatar
kooluser
1/17/2010
thanks so much for this article
Gravatar
agiboire
4/15/2010
The best way to do it it's using CSS. This example is not working with a non javascript browser.

@tchaOo°
Gravatar
Pritesh Shah
9/15/2010
hello
Gravatar
Pritesh Shah
9/15/2010
hello
Gravatar
HIFU
9/14/2011
That was a fabulous performance, congratulation to you
http://www.hifurx.com/hifu/ HIFU
Gravatar
Ignacio
11/2/2011
Great!! Thanks a lot!!!!
Gravatar
JESUS
4/20/2012
Thank you. I'm using it in a job.
Gravatar
Hadriel
6/18/2012
I know this post is kind of old, but now you can use a HTML5 attribute, 'placeholder'. This makes it even more easy.
Gravatar
lnsfhwpk
12/22/2013
1
Add a Comment

Name

Email Address

1 + 1 = ?

Comment










iphone application development konrad group
android application development konrad group
windows phone 7 development konrad group