Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
126
rated 0 times [  132] [ 6]  / answers: 1 / hits: 21271  / 15 Years ago, fri, march 12, 2010, 12:00:00

I have the password field on page. I want to display text Enter password on screen before entering password but on focus when user enter password it should go back to password type



EDIT: I am using Jquery as well so any small jquery solution will do


More From » jquery

 Answers
175

[Latest revisision to include IE support]

Update for IE9: Version 9 of IE allows the change of the type attribute for input elements of type text/password back and forth



As mentioned in the comments (and verified) the previous examples did not work in IE as it does not allow the change of the type by script ... Here is a workaround, which replaces the element with another back-and-forth (code assumes you start with a text box)



var element = document.getElementById('mysearch');

var text_to_show = 'Enter Password';

element.value = text_to_show; // set the message for the first time

element.onfocus = function(){
if (this.value == text_to_show)
{
var newElement = convertType(this);
newElement.value = '';
setTimeout(function(){document.getElementById(newElement.id).focus()},100);
}
}
element.onblur = function(){
if (this.value == '')
{
var newElement = convertType(this);
newElement.value = text_to_show;
}
}


function convertType(elem)
{
var input = document.createElement('input');
input.id = elem.id;
input.value = elem.value;
input.onfocus = elem.onfocus;
input.onblur = elem.onblur;
input.className = elem.className;
if (elem.type == 'text' )
{ input.type = 'password'; }
else
{ input.type = 'text'; }

elem.parentNode.replaceChild(input, elem);
return input;
}


[update]



scrap the original answer, i missed the part that you want to keep the field as password (with hidden contents)



Revised answer:



var element = document.getElementById('mysearch');

var text_to_show = 'Enter Password';
element.type=text; // set the type to text for the first time
element.value = text_to_show; // set the message for the first time
element.onfocus = function(){
if (this.value == text_to_show)
{
this.type=password;
this.value = '';
}
}
element.onblur = function(){
if (this.value == '')
{
this.type=text;
this.value = text_to_show;
}
}


[original answer]





var element = document.getElementById('inputID'); 
// inputID should be the ID given to the password element

var text_to_show = 'Enter Password'
element.value = text_to_show;
element.onfocus = function(){ if (this.value == text_to_show) this.value = '';}
element.onblur = function(){ if (this.value == '') this.value = text_to_show;}



[#97363] Tuesday, March 9, 2010, 15 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
phoebea

Total Points: 607
Total Questions: 100
Total Answers: 78

Location: Netherlands
Member since Thu, Jul 1, 2021
3 Years ago
;