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

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...

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

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?

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 is great! Nice blog.

Very nice script and wasn't easy to find.

Is it possible to make it work with a textarea?

Thanks

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

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.

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" />

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.

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 looks easy enough, thank you just what I was looking for.

Novak

Any way to extend this functionality to a textarea?

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.

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

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.

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

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

Hello,

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

Thanks!

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.

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.

Thanks for the contribution! I've been trying to find this functionality working with jQuery.

<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">

@Michael: adding javascript code directly to html elements is an extremely messy way to do things, non semantic and makes it a pain to update. This is the beauty of JQuery as you can keep your html clean, semantic and javascript free.

<form action ="controller.php?action=login" method="post">
<p><input type="text" name="userName" class="default-value" id="username" value="username" /></p>
<p><input type="text" name="password" class="default-value" id="password" value="password" /></p>
<br/>
<input type="submit" value="Login" class="submit" /></p>
</form>

Thanks Rob, it is really helpful I get what i wanted now.
It is kind of confusing so i give a simple way for newbie like me just do this step:
1. you need to download jquery from http://jquery.com/
2. load to ur page
you have to modify the source according to your download folder. In case you already download it to the same folder as ur html page you have no problem then
3. Then you need to modify your input class="default-value"
4. Last do not forget to add unique input id (id="password" and id="username") if you want to have multiple input form
I already give example for the form just give it a try

sorry for no.3 just add this to ur page and modify the source according to your jquery.js folder
<script type="text/javascript" src="jquery.js"></script>

Hey man thanks for the tip i have been search for a while now on how to do this!

Hello,
I tried dumping the vanilla Javascript into my HTML, but it did not work. I have worked with a bunch of server-side languages, but nothing on client-side scripting, so I am an absolute newbie at this. Is there anything else besides the copy-paste operation? I assume that the client browser must have Javascript enabled, but is there anything else to be done server-side? any files to install so that the script is recognized? Also, I do not want to install Javascript for servers-side operations, only client-side. THanks!
Cheers

Thanks for this script. I'm testing it on my website and the search box effect works great.
However, with the addition of either version of this script (with or without jquery) the loading of the web pages has slowed down and there is no longer a smooth transition from one page to the other; one page goes white before the next page loads.

I love the effect of your script and I want to keep using it, but is there a way to solve this page load slow down problem?

Thanks

Thanks for your script . I'm testing it on my website and the effect is great.
However, with the addition of either version, jquery or without it, the
loading time of the web pages has increased so that the transition of one
page into the next is no longer smooth; a page goes completely white
before the next page loads.

If this slower page loading problem can be resolved I'd love to be able to
keep using your script. Would you please suggest some way to resolve this?

Thanks

Thanks for your script. Testing it on my website the effect works great. However, with the addition of either of the two versions (with jquery or without it), the loading time of the web pages has increased so that the transition of one page into the next is no longer smooth; the screen goes completely white before the next page loads.

If this slower page loading time can be corrected I'd love to be able to continue using your script. Can you please suggest some way to remedy the issue?

Thanks

Thank you so much for your script. It's working perfectly on my website's test page. However, something on the page must be conflicting with it, as the page load is slow when the script is active; the screen goes momentarily white before it loads.
I love the effect of your script so much and I want to keep using it. Would you please point me in the right direction to a solution.

Thanks

Hi there,
Interesting tip.

Please can I confirm what the reuse terms / license this code is licensed under, please?

I'm using the javascript version of this for a work project - this has been a huge time-saver for me. Many thanks!

really nice. thanks

So, I've got the jquery version working but I'm doing something wrong. The default text shows up no problem, but it doesn't go away when I click on the search box. What haven't I done?

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