Javascript "watermarks" for textboxes

sin picture sin · Dec 16, 2009 · Viewed 14.7k times · Source

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?

Answer

Daniel Vassallo picture Daniel Vassallo · Dec 16, 2009
 <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.