SoFunction
Updated on 2025-02-28

js dynamically modify the type attribute of the input input box (implementation method analysis)

Effects that need to be achieved: an input box, when the input box does not gain focus, the value value is "password"; when the input box loses focus, the input content is displayed as "****"

<input name=”password” type=”text” id=”showPwd” tabindex=”2″ class=”input” value=”password” />

We will think of the following js

$(“#showPwd”).focus(function(){
$(this).attr(‘type','password');
});

I found that the expected effect was not achieved, and the uncaught exception type property can't be changed error occurred. Check the jQuery 1.42 source code 1488 line

// We can't allow the type property to be changed (since it causes problems in IE)
if ( name === “type” && ( ) && ) {
( “type property can't be changed” );
}

jQuery cannot modify the source JS?

$(“#pwd”).focus(function(){
$(“#pwd”)[0].type = ‘password';
$(“#pwd”).val(“”);
});

It is found that under FF, the password input box type can be modified to "password" and the value is set to empty, but under IE, the type attribute cannot be obtained and this command is not supported. Pop up type and see if it really can't be obtained?

$(“#showPwd”).focus(function(){
alert($(“#showPwd”)[0].type);
$(“#showPwd”)[0].type = ‘password';
$(“#showPwd”).val(“”);
});

I found that the text popped up, but it was not impossible to get it, but it could not be modified under IE. Therefore, we thought of removing first and then generating a password input box with type password.

The following type is the input box for password

<input name=”password” type=”password” id=”password” class=”input” style=”display: none;” />

$(“#showPwd”).focus(function() {
var text_value = $(this).val();
if (text_value == ) {
$(“#showPwd”).hide();
$(“#password”).show().focus();
}
});
$(“#password”).blur(function() {
var text_value = $(this).val();
if (text_value == “”) {
$(“#showPwd”).show();
$(“#password”).hide();
}
});

Final effect: When the input box gets focus, the input content is displayed as "****"; when the focus is lost, the "password" is displayed when the content is empty.