Q_24713072: Make a switchable textbox from visible to password

In Internet Explorer, the type of a password input element is protected, hence you cannot change it by calling setAttribute or the type member variable. Instead, you need a tricky workaround with the only-IE extension outerHTML (other workarounds are possible too) which is a bit involved. Just try it out.

This page will remain online for future reference. The original question can be viewed at Experts-Exchange, but requires (free) membership. More information about me, about how this site is maintained and about how to use these pages for yourself, check out the opening page.

Use the following code:

After you set outerHTML, the element is taken from the DOM and inserted in the DOM again, hence you must use getElementById again. Note that the search string "type=password" is not XHTML, but HTML 3 syntax, which is what Internet Explorer uses as internal representation.

<script type="text/javascript">
    function switchPass() {
        var pass = document.getElementById('thepassword');
        var oldType = pass.getAttribute("type");
        var newType = oldType == "text" ? "password" : "text";

        try {
            pass.setAttribute("type", newType)
            
        } catch (e) {
            
            // workaround for IE, who raises an error here                
            var passValue = pass.value;
            pass.outerHTML = pass.outerHTML.replace(new RegExp('type=' + oldType), newType);

            // need to get it again
            pass = document.getElementById('thepassword');
            pass.value = passValue;
        }
    }
</script>

Try it out yourself by typing something and clicking the "switch" button