简体   繁体   中英

default value 'password' for input field, show it?

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

您是否在考虑<input placeholder='Password' type='password'/>

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" />​

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM