Category Archives: Tutorials

Using jQuery to Handle Dynamic Default Text in Form Fields

Download a working demo here (.zip)

It’s very common to want to add default text to a textarea or text input field and have that text vanish when a user clicks to edit the field. When the user clicks away from the field, if the field is still empty, we should bring back the default text. This is easy to do using the jQuery JavaScript Library.

The Code

HTML

We start by adding a ‘defaultText’ class to our textarea and input fields that will contain default text–and adding a title attribute with the default text for these elements:

<form name="someForm">
<input type="text" name="user" class="defaultText" value="" title="enter your name..." />
<textarea name="bio" class="defaultText" title="enter your bio..."></textarea>
</form>
<!-- don't forget to include jquery -->
<script type="text/javascript" 
src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js">
</script>

JavaScript

Now we use jQuery to find all elements with the ‘defaultText’ class and add the focus and blur handlers:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
/**
 * Setup handlers on elements when the document is ready 
 */
$(document).ready( function(){
   // add the focus handler to all elements with a class of 'defaultText'
   $(".defaultText").focus( function(e){
      // if the field contains the default text, clear it
      if(this.value == $(this).attr('title')) {
         this.value = '';
      }
      $(this).removeClass('defaultText'); // remove special styling
   }).blur( function(e){ // add the blur handler
      // if the user leaves the field without entering anything, bring back the default text
      if(this.value == ""){
         $(this).addClass('defaultText'); // bring style back
         this.value = $(this).attr('title');
      }
   }).blur(); // invoke the blur handler, which copies the title to the value
});

CSS

Don’t forget to style your defaultText class so that it looks a little different from user supplied text:

.defaultText {
    font-size:12px;
    color:#999;
}

Download a working demo here (.zip)

follow on Twitter