Home > Web Front-end > JS Tutorial > body text

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

Linda Hamilton
Release: 2024-11-16 05:08:03
Original
613 people have browsed it

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');
});
Copy after login

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";
Copy after login

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';
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template