default value 'password' for input field,

2019-05-17 21:59发布

I'm using this js to display default password, when user clicks it automatically clears default value, if user deselects without entering anything default value re-appears.

I used it for all my fields, but obviously for password it is trickier! :)

How would you do it?

<input
    type="password"
    onblur="this.value=!this.value?'Password':this.value;"
    onfocus="this.select()"
    onclick="if (this.value=='Password'){this.value='';}"
    name="pwd"
    id="user_pass"
    class="input"
    value="Password"
    size="20"
    tabindex="20" />

5条回答
We Are One
3楼-- · 2019-05-17 22:36

Please use the below solution,

<input name="password" class="input"value="Password" size="20"
  tabindex="20"  onclick="if(this.value==defaultValue){this.value=''; this.type='password'} else if(this.value==''){this.value=defaultValue; this.type='text'} " onblur="if(this.value==''){this.value=defaultValue; this.type='text'}"/>

because first solution works well but if u empty the password field, it will not convert to its default value which is a text. So try above solution.

查看更多
迷人小祖宗
4楼-- · 2019-05-17 22:39

You need to create a plain text input as a placeholder. This code will do that for you without exposing any variables to the global scope:

​<input id="pass-placeholder" type="text"​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​ value="Password" />
<script type="text/javascript">
(function(){
    var pass_holder_el = document.getElementById('pass-placeholder');
    var pass_el = document.createElement('input');
    pass_el.type = 'password';

    pass_el.onblur = function(){
        if(!this.value)
            this.parentNode.replaceChild(pass_holder_el, this);
    }

    pass_holder_el.onfocus = function(){
        this.parentNode.replaceChild(pass_el, this);
        pass_el.focus();    
    }
})();
</script>​

JSFiddle

查看更多
Emotional °昔
5楼-- · 2019-05-17 22:49

Were you thinking of <input placeholder='Password' type='password'/> ?

查看更多
Evening l夕情丶
6楼-- · 2019-05-17 22:50

This is your solution: http://jsfiddle.net/cgP5K/1/

<input
  type="text"
  onblur="this.value=!this.value?'Password':this.value;"
  onfocus="this.select()"
  onclick="if (this.value=='Password'){this.value=''; this.type='password'}"
  name="pwd"
  id="user_pass"
  class="input"
  value="Password"
  size="20"
  tabindex="20" />​
查看更多
登录 后发表回答