Home >Web Front-end >JS Tutorial >Why Can\'t I Change an Input Field\'s \'type\' from Password to Text with jQuery?

Why Can\'t I Change an Input Field\'s \'type\' from Password to Text with jQuery?

Linda Hamilton
Linda HamiltonOriginal
2024-11-16 05:08:03703browse

Why Can't I Change an Input Field's 'type' from Password to Text with jQuery?

Change Type of Input Field with jQuery: Why It May Not Work

When attempting to modify an input field from a password type to a text type using jQuery, you may encounter an issue where the change is not taking effect.

Here's the code in question:

$(document).ready(function() {
    // #login-box password field
    $('#password').attr('type', 'text');
    $('#password').val('Password');
});

This code aims to change the input field with an id of "password" to a text field and then populate it with the text "Password." However, it may fail due to the browser's security model.

Testing in Safari shows an error indicating that the type property cannot be changed. This is also supported by the jQuery source code, which contains a check:

if ( name == "type" && jQuery.nodeName( elem, "input" ) && elem.parentNode )
    throw "type property can't be changed";

This check prevents the type property from being changed for input fields in Internet Explorer. It's unclear whether this is a bug or a security design choice.

To overcome this issue, you can use native DOM manipulation instead of jQuery. Here's how:

var pass = document.createElement('input');
pass.type = 'password';
document.body.appendChild(pass);
pass.type = 'text';
pass.value = 'Password';

This code will successfully change the input field to a text type and populate it with the specified value.

The above is the detailed content of Why Can\'t I Change an Input Field\'s \'type\' from Password to Text with jQuery?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn