How to Make a Show Password Link with JQuery

While we all agree a good security measure is hiding passwords in form inputs, giving a user the ability to unhide the password is a nice usability feature. How often are you changing your password with nefarious people standing over your shoulder, right?

Really, the difference between markup for a text field and password field is just the type attribute of either 'text' or 'password'. JQuery makes it easy to work with attributes, by the $().attr() method. So, this would seemingly be a very simple task, right? Let's try it:

view plain print about
1<script type="text/javascript>
2 oldBox.attr('
type', 'text');
3</script>
Whoa, this promptly results in the following error:

uncaught exception: type property can't be changed

Ouch. That didn't work like we expected, did it? Let's look at why. Once an element is inside the DOM, the type of the element can't be changed. The differences between the various DOM controls just mean we can't change a type of an element once it has been added. We can, however, clone the element, change the type then attach it to the DOM and it will work perfectly.

[More]

There are no comments for this entry.

Add Comment Subscribe to Comments

12/4/09 8:21 AM # Posted By Tony Nelson

I ran into this same thing a couple weeks ago.

&lt;script type="text/javascript"&gt;
   showPassword = function() {      
      document.getElementById('password').type = document.getElementById('password').type == 'password' ? 'text' : 'password';      
   }
&lt;/script&gt;

&lt;input type="password" id="password" value="this-is-my-password" /&gt;

&lt;button onclick="showPassword();"&gt;Toggle Password&lt;/button&gt;

This works in Firefox (and without the need for jQuery), but not in IE. I ended up having to render a secondary field similar to how you're doing it.


12/4/09 8:32 AM # Posted By John Hodorowicz

If you need to view your password and you're on a site that doesn't offer this option you can use the Web Dev Toolbar in FF: Forms -> Show Passwords


12/4/09 5:57 PM # Posted By James Moberg

I found this while looking for an easy plug-and-play solution:
http://andreaslagerkvist.com/jquery/show-password/...