I have a textbox.

Now when the page is opened i want the textbox to have a default value.Once he click on the textbox the value should disappear and again when he removes his cursor from the text box ,the old value should come back.

So how do i do this ?


Accepted Answer

Add a specific class to all textboxes on the page that you want to have this functionality.

Then, use this code to apply the functionality to the elements that have the class:

window.onload = function() {
   var elements = document.querySelectorAll('.yourClassName');
   for(var i = 0, j = elements.length; i < j; i++) {
      var element = elements[i]; 
      element.onfocus = function() {
         this.value = '';
         this.style.color = 'black';
      element.onblur = function() {
          if(this.value == '') {
             this.value = this.getAttribute('defaultValue');
             this.style.color = 'grey';

Working example: http://jsfiddle.net/6TmGA/1/

Written by Jacob Relkin
This page was build to provide you fast access to the question and the direct accepted answer.
The content is written by members of the stackoverflow.com community.
It is licensed under cc-wiki