The browser compatibility issues continue. For some time there has been a problem dynamically changing an input element from text to password (and vice-versa). In most browsers (Chrome, FireFox included) this is a very simple task:
var elem = document.getElementById('myInputBox');
elem.type = 'password';
In *uhem* Internet Explorer (IE) this will throw an exception, as changing the type attribute directly is not possible.
The solution I have come up with is far from foolproof so use it at your own risk. It only has basic error checking and has only been tested on PC (IE8, Chrome5, FireFox3).
It works by creating a new input element, setting the 'type' attribute, and then copying across the name, id, value and style attributes from the original element. It then uses teh DOM to completely replace the old element with the new one.
Note that it does not copy ALL attributes, so if there is anything you want to keep from the old element to the new one, add it to the function manually. In my case I ensure that onfocus and onblur are retained, for example, and you may also want to keep onclick or other events.
function invChangeInputType( elem, newType ){
if (elem.type==newType) return elem;
try{
elem.type=newType;
}catch(e){
if (document.createElement && elem.replaceNode){
var onFocus = elem.onfocus;
var onBlur = elem.onblur;
elem.onfocus = null;
elem.onblur = null;
var newElem = document.createElement("input");
newElem.type = newType;
newElem.name = elem.name;
newElem.id = elem.id;
newElem.value = elem.value;
newElem.className = elem.className;
for(var prop in elem.style){
newElem.style.setAttribute( prop, elem.style.getAttribute( prop ) );
}
elem.replaceNode(newElem);
newElem.onblur = onBlur;
newElem.onfocus = onFocus;
return newElem;
}
}
return elem;
}
var elem = document.getElementById('myInputBox');
elem = changeInputType(elem,'password');