7

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?

Daniel Vassallo
  • 337,827
  • 72
  • 505
  • 443
sin
  • 71
  • 1
  • 1
  • 3

6 Answers6

19
 <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
  • 337,827
  • 72
  • 505
  • 443
7

A more modern way is to use "PlaceHolder"

<input type="text" placeholder="search" />
Jason Geiger
  • 1,912
  • 18
  • 32
4

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
  • 115,835
  • 26
  • 236
  • 269
4

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
  • 31,209
  • 11
  • 51
  • 83
0

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
  • 24,791
  • 9
  • 70
  • 92
  • Don't use the 'onfocus' attribute. Use events instead – Pablo Fernandez Dec 15 '09 at 23:51
  • 2
    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 Dec 16 '09 at 00:00
0

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

Chetan S
  • 23,637
  • 2
  • 63
  • 78