Cloning and changing the TYPE attribute of an INPUT element

Cool snippet I found here, which was helpful in building Ekkio’s login forms.

ekkio login form

Notice that the password field is really a text field when the page loads – it does not mask characters. However, once the the field has focus and the user beings typing his password, masking is expected, so the field is transformed into a password field. This is trickier than it sounds because you can’t change the type attribute of an input element.

A possible solution is to clone the input element, then change the type attribute of the clone.

var clone = $('#login_field_password').clone(); clone.attr('type', 'password'); clone.attr('id', 'new_login_field_password'); clone.insertBefore($('#login_field_password')); $('#login_field_password').remove(); clone.attr('id', 'login_field_password'); $('#login_field_password').val(''); $('#login_field_password').css('color', '#000'); $('#login_field_password').focus();

You clone the field, change the type attribute of the clone, then delete the original. Unfortuantely, this doesn’t work in IE, as even changing the type attribute of a clone is not allowed. The only solution I’ve found so far is to clone manually by actually writing the HTML markup with the new type:

var clone = $('<input id="new_login_field_password" name="password" type="password" />');

This works but it’s not as versatile. The revised code is shown below.

var clone = $('<input id="new_login_field_password" name="password" type="password" />'); clone.attr('id', 'new_login_field_password'); clone.insertBefore($('#login_field_password')); $('#login_field_password').remove(); clone.attr('id', 'login_field_password'); $('#login_field_password').val(''); $('#login_field_password').css('color', '#000'); $('#login_field_password').focus();