views:

52

answers:

3

Guys,

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 ?

Thanks

+4  A: 

Can you use jQuery?

If you can there are a lot of plugins that will help with this.

such as;

http://www.jason-palmer.com/2008/08/jquery-plugin-form-field-default-value/

griegs
You can add a focus event to the element using javascript and then check for a value etc. lot more work than using jQuery and a plugin.
griegs
+4  A: 

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';
          }
      };
      element.onblur();
   }
};
​

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

Jacob Relkin
I just want a simple HTML guys !! No jQuery and other complex stuff :p
5416339
HTML cannot do that all by itself.
Yehonatan
Simplicity is the key guys : onblur='if (this.value == "") {this.value = "To search, type and hit enter";}' onfocus='if (this.value == "To search, type and hit enter") {this.value = "";}'
5416339
@5416339, Witness the power of my approach: http://jsfiddle.net/6TmGA/
Jacob Relkin
But mine is way simpler mate.Not that i don't appreciate yours !
5416339
And it does the same thing in less steps !!
5416339
@5416339 "But mine is simpler..." Not when you're breaking best practices. Please, please, don't use inline Javascript events. Behavior shouldn't be floating around with the rest of your HTML content.
Yi Jiang
A: 
function setFocus() { document.getElementById('username').focus(); }
Dharmendra Katariya
1. That's not the correct answer to this problem (read the question again, carefully. This doesn't answer it) 2. Use the correct formatting for your code (four spaces to create a code block) 3. When answering, try to give some explanation as to what your actually doing here, or link to the appropriate documentation
Yi Jiang