Realizing that my original solution would not work, I spent some time trying to find a working solution only out of curiosity. I would still recommend using the jQuery eKek0 plugin , as it gets worse.
The following example is quite flexible. Instead of hard-coding the replacement <input /> tags as strings, replacement tags are made from the original tags. This helps if the attributes of the <input /> changed since you will not lose any style or other attributes assigned to the tags.
The following solution was tested on 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 <input /> with the appropriate type of blur and focus. It also adds / removes a class to stylize the placeholder text โpasswordโ, therefore it is more useful because the text โpasswordโ of the placeholder is not the default black color, which could potentially be misleading for the user.
You can see how it works here: http://jsbin.com/azugu
Dan herbert
source share