Travis Collins

Dramatic Password Reveal - in ASP.NET

Jeff Atwood recently blogged about a nice feature of Vista, when you are entering your wireless network key.  This feature provides the user with a checkbox to toggle the obfuscation of the wireless key being entered.

As Jeff mentions, this is a nice technique, and one that I have recently investigated for my own web applications. However, doing this on the web is a little trickier because you aren't able to change the type attribute of an input element using JavaScript.  Shown below, I have developed a way to accomplish the same result.

First, surround your password text field with a simple span

<span id="spanPass"><asp:TextBox ID="Password" runat="server" TextMode="Password" CssClass="txt" /></span>

Add a checkbox to toggle the password obfuscation

<input type="checkbox" id="chkReveal" onclick="toggleReveal();" /><label for="chkReveal">Reveal my password</label>

 

Finally a bit of JavaScript, and we're done

<script type="text/javascript">
    function toggleReveal()
    {
        var chkReveal = $get('chkReveal');
        var txt = $get('<%= this.Login1.FindControl("Password").ClientID %>');
        var spanPass = $get('spanPass');
        
        if (chkReveal.checked)
            spanPass.innerHTML = '<input type="text" name="' + txt.name + '" id="' + txt.id + '" value="' + txt.value + '" class="'+ txt.className +'" />';
        else
            spanPass.innerHTML = '<input type="password" name="' + txt.name + '" id="' + txt.id + '" value="' + txt.value + '" class="'+ txt.className +'" />';
    }
</script>

Note I am using the handy $get which comes with ASP.NET AJAX.  If you are not using this framework, you can just as easily replace $get with document.getElementById(). 

This small JavaScript method simply rewrites the contents of the span tag with a new input control, copying the previous name, id, value, and class values.  The only thing that gets changed is the type attribute.  Now I know what you're thinking, and no, JavaScript is not able to change the type attribute directly.

I have tested this in IE6, IE7, Firefox and Safari.  It works as expected in all of these browsers.

Comments

No Comments