Javascript “watermarks” for textboxes [duplicate]

2019-01-19 17:22发布

This question already has an answer here:

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?

6条回答
聊天终结者
2楼-- · 2019-01-19 17:26
 <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.

查看更多
ゆ 、 Hurt°
3楼-- · 2019-01-19 17:28

A more modern way is to use "PlaceHolder"

<input type="text" placeholder="search" />
查看更多
女痞
4楼-- · 2019-01-19 17:32

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.

查看更多
我只想做你的唯一
5楼-- · 2019-01-19 17:33

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" />
查看更多
三岁会撩人
6楼-- · 2019-01-19 17:40

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

查看更多
够拽才男人
7楼-- · 2019-01-19 17:48

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".

查看更多
登录 后发表回答