default value 'password' for input field,

2019-05-17 22:26发布

问题:

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

回答1:

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


回答2:

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



回答3:

Try This out - http://roshanbh.com.np/examples/text-in-password/



回答4:

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



回答5:

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.