Visit Sponsor

Written by 7:14 am Ajax, Javascript

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:


Here are the important parts of the script:

  1. oldBox.clone() – replicates the DOM element we want to change. We can then change the type attribute of newBox all we want to because the cloned one isn’t attached to the DOM
  2. newBox.attr(“type”, ( oldBox.attr(‘type’)==’password’?’text’:’password’ ) ) – toggles between the types of password and text. (Don’t let your eyes bleed, this is a simple ternary operation…)
  3. newBox.insertBefore(oldBox) injects the newBox element (with our new fancy type) into the DOM.
  4. oldBox.remove() – removes the oldBox.

So, while we can’t change certain parts of DOM elements directly, by using clone, we can pretty much do whatever we want to. Happy JQuerying!


Visited 1 times, 1 visit(s) today
[mc4wp_form id="5878"]
Close