views:

233

answers:

5

I would like to know how to put text in a textbox when the page loads. Example: If I have a login page, I would have 2 textboxes named "username" and "password". When the page loads I want the the textbox to load with "username" written inside, so I won't have to put a label for that outside. But when the user clicks inside textbox it should disppear. How do I do this?

+13  A: 
 <input name="q" onfocus="if (this.value=='search') this.value = ''" type="text" value="search">

...from the Stack Overflow search box.


You could also add the onblur event to check: if (this.value=='') this.value = 'search'

This would re-print the watermark when the user clicks outside the textbox and the field is empty.

Daniel Vassallo
+1 for simplicity.
Brandon
I would also make the text more grayish and not black
Faruz
+2  A: 

There are a lot of tutorials on how to do this. Here's one walkthrough using the jQuery javascript framework.

Here's another popular blog post about it, just using regular javascript.

womp
A: 

JS:

   function clearDefault(ctl){
       if(ctl.value==ctl.defaultValue) { ctl.value = ""; }
    }

In your textbox include onfocus="clearDefault(this)" and set its text to "username" or "password".

jball
Don't use the 'onfocus' attribute. Use events instead
Pablo Fernandez
The `onfocus` (as well as `onblur`) attributes are essentially events. Their values are equal to the body of a function bound to the event. So having `clearDefault(this)` for the `onfocus` is essentially having this bound as your `focus` event handler:`function() { clearDefault(this); }`
Mark Ursino
A: 

See this article http://www.alistapart.com/articles/makingcompactformsmoreaccessible. Of course, if you are using jQuery, there are "Label over" plugins.

Chetan Sastry
+1  A: 

In laymen's terms:

  • When focusing on the input, if the value is "Username" then set it to ""
  • When removing focus from the box, if the value is "" (i.e. nothing was entered), reset it to "Username" to still provide feedback to the user since they haven't yet entered data

The code:

<input value="Username" onfocus="if(this.value=='Username') this.value = ''" onblur="if(this.value=='') this.value = 'Username'" type="text" />
Mark Ursino