After realizing my original solution wouldn't work, I spent a while trying to come up with a working solution just out of curiosity. I'd still recommend using the jQuery plugin eKek0 recommended, since it degrades better, though.
The following example is fairly flexible. Rather than hard-coding the replacement <input />
tags as strings, the replacement tags are derived from the original tags. This helps if the <input />
tag attributes are altered, since you won't lose any styling or other attributes given to the tags.
The following solution has been tested in Chrome, Firefox, IE8, and IE8 in IE7 compatibility mode.
$(document).ready(function() {
var focusEvent = function() {
if(this.type == 'text') {
var html = $(this).clone().wrap('<span></span>').parent().html();
html = html.replace(/type=("|')?text("|')?/, 'type="password"');
var $newPwdBx = $(html);
$(this).replaceWith($newPwdBx);
$newPwdBx.removeClass('readOnly');
$newPwdBx.val('');
$newPwdBx.focus();
$newPwdBx.blur(blurEvent);
}
};
var blurEvent = function() {
if(this.value == '') {
var html = $(this).clone().wrap('<span></span>').parent().html();
html = html.replace(/type=("|')?password("|')?/, 'type="text"');
var $newTxtBx = $(html);
$(this).replaceWith($newTxtBx);
$newTxtBx.addClass('readOnly');
$newTxtBx.val('password');
$newTxtBx.focus(focusEvent);
}
};
$("#password").focus(focusEvent);
});
This code replaces the <input />
with the appropriate type on blur and focus. It also adds/removes a class for styling the "password" placeholder text so it is more usable, since the placeholder "password" text is not the default black color, which could potentially be misleading to a user.
You can see it working here: http://jsbin.com/azugu