Javascript watermark for text fields

I would like to know how to put text in a text box when loading a page. Example. If I have a login page, I will have 2 text fields with the name "username" and "password". When the page loads, I want the text box to load with the "username" written inside, so I don’t need to put a shortcut for this outside. But when the user clicks inside the text box, he needs to print. How to do it?

+7
javascript watermark
source share
6 answers
<input name="q" onfocus="if (this.value=='search') this.value = ''" type="text" value="search"> 

... from the Stack Overflow search box.


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

This will re-print the watermark when the user clicks outside the text field and the field is empty.

+19
source share

A more modern way is to use "PlaceHolder"

 <input type="text" placeholder="search" /> 
+5
source share

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

Here's another popular blog post about this, just using plain javascript.

+4
source share

In the conditions of the laity:

  • When you focus on the input, if it is "Username", set it to ""
  • When removing focus from the window, if the value is "(i.e. nothing has been entered), reset it should be" Username "in order to still provide feedback to the user, since they have not entered the data yet.

The code:

 <input value="Username" onfocus="if(this.value=='Username') this.value = ''" onblur="if(this.value=='') this.value = 'Username'" type="text" /> 
+4
source share

JS:

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

In your text box, enter onfocus="clearDefault(this)" and set its text to "username" or "password".

0
source share

See the article http://www.alistapart.com/articles/makingcompactformsmoreaccessible . Of course, if you use jQuery, there are plugins labeled "Captions."

0
source share

All Articles