Entering default text for password field
Is there a way to enter a default text to a password field?
Basically I have a password field that is supposed to m开发者_C百科ask someone's id but before the user enteres the id, I want the field's value to show 'Enter your ID here'
Is there a way to do this?
If you want to use plain javascript, you could do:
HTML
<label for="placeholder">Password:</label>
<input type="text" id="placeholder" value="Enter password here" onFocus="setPass();"/>
<input type="password" id="password" value="" onBlur="checkPass();" style="display: none;"/>
Javascript
function setPass() {
document.getElementById('placeholder').style.display = 'none';
document.getElementById('password').style.display = 'inline';
document.getElementById('password').focus();
}
function checkPass() {
if (document.getElementById('password').value.length == 0) {
document.getElementById('placeholder').style.display = 'inline';
document.getElementById('password').style.display = 'none';
}
}
http://jsfiddle.net/Lx4NN/1/
At this moment if you want to support all types of browsers (that have enabled JavaScript), you should use JavaScript. I believe there a some scripts you could use, but writing one yourself is a good option too of course. In an earlier stage I have written a script myself to do this where I changed the TYPE field of the input to 'text' when no password was entered. When a user focused on the password field, the type was changed back to 'password'.
Mind Internet Explorer: I believe 7 and below do not allow you to change the type of the field. But any other decent browser does.
If your requirement is that browsers that support at least HTML 5 should be able to use it, have a look at HTML 5 placeholders. I think it does exactly what you want as well.
Check this link for more info, it has some info on placeholders as well. Have fun! ;)
<input type="text" value="Enter your ID here"
onfocus="if (this.value == 'Enter your ID here') this.value = ''"
onblur="if (this.value == '') this.value = 'Enter your ID here'"
/>
精彩评论