Default text field value that disappears on focus

06-Dec-2007
Filed under: JavaScript, jQuery

See the search form top right? Click the search box. See how the default text disappears and then reappears when you click away from the search box? Here's how you do it.

The script below searches the page that it's inserted on for all form input fields that have a class of default-value applied. Each form input field must have a unique ID.

When the page loads the script changes the color of the text in the text fields it has found to the value of inactive_color. If the user clicks on the input field, the default text is blanked, and the colour changed to 'active_color'. If the user clicks away from the input field, i.e. the input field loses focus, the value of the text field will revert back to the original text, and the colour will change back to 'inactive_color', unless the user has entered some other text.

I've provided by a jQuery version, and a vanilla JavaScript version for those of you who aren't already including the jQuery library.

First, the jQuery version:

<script type="text/javascript">
/**
* Written by Rob Schmitt, The Web Developer's Blog
* http://webdeveloper.beforeseven.com/
*/

/**
* The following variables may be adjusted
*/
var active_color = '#000'; // Colour of user provided text
var inactive_color = '#ccc'; // Colour of default text

/**
* No need to modify anything below this line
*/

$(document).ready(function() {
  $("input.default-value").css("color", inactive_color);
  var default_values = new Array();
  $("input.default-value").focus(function() {
    if (!default_values[this.id]) {
      default_values[this.id] = this.value;
    }
    if (this.value == default_values[this.id]) {
      this.value = '';
      this.style.color = active_color;
    }
    $(this).blur(function() {
      if (this.value == '') {
        this.style.color = inactive_color;
        this.value = default_values[this.id];
      }
    });
  });
});
</script>

And here's the ordinary JavaScript version:

<script type="text/javascript">
/**
* Written by Rob Schmitt, The Web Developer's Blog
* http://webdeveloper.beforeseven.com/
*/

/**
* The following variables may be adjusted
*/
var active_color = '#000'; // Colour of user provided text
var inactive_color = '#ccc'; // Colour of default text

/**
* No need to modify anything below this line
*/
window.onload = formDefaultValues;

function formDefaultValues() {
  var fields = getElementsByClassName(document, "input", "default-value");
  if (!fields) {
    return;
  }
  var default_values = new Array();
  for (var i = 0; i < fields.length; i++) {
    fields[i].style.color = inactive_color;
    if (!default_values[fields[i].id]) {
      default_values[fields[i].id] = fields[i].value;
    }
    fields[i].onfocus = function() {
      if (this.value == default_values[this.id]) {
        this.value = '';
        this.style.color = active_color;
      }
      this.onblur = function() {
        if (this.value == '') {
          this.style.color = inactive_color;
          this.value = default_values[this.id];
        }
      }
    }
  }
}

/**
* getElementsByClassName()
* Written by Jonathan Snook, http://www.snook.ca/jonathan
* Add-ons by Robert Nyman, http://www.robertnyman.com
*/

function getElementsByClassName(oElm, strTagName, strClassName){
  var arrElements = (strTagName == "*" && oElm.all)? oElm.all : oElm.getElementsByTagName(strTagName);
  var arrReturnElements = new Array();
  strClassName = strClassName.replace(/\-/g, "\\-");
  var oRegExp = new RegExp("(^|\\s)" + strClassName + "(\\s|$)");
  var oElement;
  for (var i = 0; i < arrElements.length; i++) {
    oElement = arrElements[i];
    if (oRegExp.test(oElement.className)) {
      arrReturnElements.push(oElement);
    }
  }
  return (arrReturnElements);
}
</script>

Comments

thanks for this contribution. i will pass this link to my newsletter subscribers.

Repost - forgot my tags...

Napo: The best way to learn is to play with it. hehe...I mean, the script. This page is a working example, just view the source of the page. Do a search for jquery library. First link should bring you to a download. And as you can see from reviewing the code on this page, in the [head] tags you'll see [script type="text/javascript" src="/misc/jquery.js">script] simply mirror that path on your server, and presto!!! That's what I did anyway, seems to work great.

Napo: The best way to learn is to play with it. hehe...I mean, the script. This page is a working example, just view the source of the page. Do a search for jquery library. First link should bring you to a download. And as you can see from reviewing the code on this page, in the tags you'll see simply mirror that path on your server, and presto!!! That's what I did anyway, seems to work great.

Hello,

Where can I find a working sample?
I don't seem to know how to install this script.

Thanks!

Nevermind, the last function was part of your script. :-) I still need help making this work with a textarea.

I would appreciate instructions for making the "vanilla" version work with textareas. Not using getElementsByClassName.

Rob - Nevermind, I figured it out -- I downloaded the latest version of the getElementsByClassName, and pass it "default-value" as the only parameter. Working perfectly on a page with mixed input/textarea elements.

Rob - this is great. I'm not familiar enough with the getElementsByClassName function to extend this functionality to textarea fields. Could you post the changes to the vanilla javascript version that are needed to make this work?

I've got a bunch of pages with 2 or 3 input fields and one textarea element, and it would be great to have a uniform way to indicate what goes in each field (right now the textarea needs an external label, whereas i have the disappearing default-value working in the input fields.

Thanks in advance,

JJ

Hi Dave,

Yup, that's actually pretty easy. For the jQuery version, simply change the two lines that begin with:

$("input.default-value")[...]

To the following:

$(".default-value")[...]

This will apply the script to ANY element with a class of 'default-value'. Let me know if you'd like some help with the vanilla JavaScript version.

Any way to extend this functionality to a textarea?

This looks easy enough, thank you just what I was looking for.

Novak

Hi,

I am trying to apply this implementation to "comments" form on my Wordpress blog.

I have four fields,

1 - Name (required)
2 - E-mail (required)
3 - Website (optional)
4 - Message (..ummm)

The problem I am facing is that by having default text in the "name" field especially, means that a user can still submit the form successfully using the default text of "Name" and his/her actual Name.

Is there a way to prevent this and ensure that the user actually enters something other than the default value?

Regards,
Ace

this script really solved a headache for me... i was trying to figure out how i can implement this... tried big modules, and other stuff... but this is really very simple and effective.... JavaScript... i should have thought of it!!! thanx once again.

if u want just a simple input form value that just disapear when you focus your cursor just use this

<input onfocus="this.value=''" type="text" value="some text" />

or this

<input onfocus="this.select()" type="text" value="some text" />

Thanks for your contribution, Michael. Your method works very well, though I'd still stick with my own method. I accept it's just preference my preference, but I like to avoid inline JavaScript when I have the choice.

Hi i just thought i would trow my to pence in and say that this functionality can be achieved right on the form element (this is good because you may have different element on the same page with different behavior). you can use this simple text field code to achieve it without putting your large script on the page.
<input name="keyword_" type="text" size="25"  style="color:#999;" maxlength="128" id="keyword_"
onblur="this.value = this.value || this.defaultValue; this.style.color = '#999';"
onfocus="this.value=''; this.style.color = '#000';"
value="Search Term">
notice the style attribute has the default colour for the box value on page load then the onfocus and onblur will toggle the colour for that element. i just thought i would share this with you and any one else. cheers michael

Very nice script and wasn't easy to find.

Is it possible to make it work with a textarea?

Thanks

This is great! Nice blog.

Thanks for pointing out the bug that occurs when you try to use multiple input fields on the same page.

I forgot to mention that each form field requires a unique ID. That is all you need to change to get the script working properly. I have updated my instructions accordingly.

I found another little bug in the ordinary JavaScript version of the script and have fixed this too.

This script currently doesn't support multiple input boxes with different names. If they have the same name it will work for them, if they don't it will just act like a normal default value.

This affects the first box clicked on so if I have four input boxes with the values One, Two, Three, Three; if I click on One after page load it will act as it should, but only for that field. If I click on three, it will work for both the input boxes with the value Three, but none of the others.

Is there a way to fix this?

wait nvm I get it now. I'm supposed to enter "default-value" for the input class.

I like this script very much but I'm having trouble getting it to work. How do I use it exactly? Do I place it in the section? or the section? Do I need to change anything in my form? please help me...

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.
  • Allowed HTML tags: <i> <b> <cite> <code>
  • Lines and paragraphs break automatically.
  • You may post code using <code>...</code> (generic) or <?php ... ?> (highlighted PHP) tags.
CAPTCHA
Are you human?