Home > Article > Web Front-end > js dynamically modifies the type attribute of the input box (implementation method analysis)_javascript skills
The effect to be achieved: an input box. When the input box does not gain focus, the value is "password"; when the input box loses focus, the input content is displayed as "*****"
We will directly think of the following js
$("#showPwd").focus(function(){
$(this).attr('type','password');
});
It was found that the expected effect was not achieved, and an uncaught exception type property can't be changed error occurred. Check jQuery 1.42 source code line 1488
// We can't allow the type property to be changed (since it causes problems in IE)
if ( name === “type” && rtype.test( elem.nodeName ) && elem.parentNode ) {
jQuery.error( “type property can't be changed” );
}
What if jQuery can’t modify Yuansheng’s JS?
$("#pwd").focus(function(){
$("#pwd")[0].type = 'password';
$("#pwd").val( "");
});
I found that under FF, I can modify the password input box type to "password" and set the value to empty, but under IE, it prompts that the type attribute cannot be obtained and this command is not supported. Pop the type to 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. It turned out that it was not impossible to get it, but it could not be modified in IE. Therefore, we thought that we could remove first and then generate a password input box whose type is password.
The following input box of type password
$(“#showPwd”).focus(function() {
var text_value = $(this).val();
if (text_value == this.defaultValue) {
$( "#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 gains focus, the input content is displayed as "****"; when it loses focus, "password" is displayed when the content is empty.