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:
- 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
- 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…)
- newBox.insertBefore(oldBox) injects the newBox element (with our new fancy type) into the DOM.
- 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!