繁体   English   中英

以编程方式将文本框类型从 type='text' 更改为 type='password'

[英]programatically change textbox type from type='text' to type='password'

我有用户名和密码文本框。 我希望它们都显示默认文本,即“用户名”和“密码”,但是当用户单击密码框时,出于安全原因,它应该动态更改为“密码”类型。

我已经设法用 javascript 代码很容易地做到这一点,但它不想在 IE 中工作。

<input id="username" class="username" name="u" type="text" value="username" onclick="if(this.value='username') {this.value=''};" />
<input id="password" class="password" name="p" type="text" value="password" onclick="if(this.value='password') {this.value=''; this.type='password'};" /> 

假设您的 html 代码是这样的

<input type="text" id="txtId" />

您可以使用 Jquery 替换它,

$('#txtId').replaceWith('<input type="password" id="txtId" />')

IE 只允许您在创建元素时设置一次input元素的类型。 之后尝试设置它会失败。

如果您想在 IE 中“更改”元素,您可能需要做的是创建另一个具有相同属性的元素(当然类型除外),并用它替换现有元素。

或者为密码创建一个虚拟文本框,并隐藏真正的密码框——在焦点上,虚拟框应该隐藏自己,并显示并关注真正的密码框。

您会考虑使用 JQuery 吗?

$("[name=fieldname]").attr("type", "password");

这对我有用 把它放在头部

function changeBack()
 {
     if(document.getElementById('smsl_pw').value=='')
     {
        document.getElementById('smsl_pw').type='text';
        document.getElementById('smsl_pw').value='Password';

     }

 }

 function changePass()
 {
    document.getElementById('smsl_pw').type='password'; 
    document.getElementById('smsl_pw').value='';

 }

这是输入字段<input id="smsl_pw" onclick="changePass();" onblur="changeBack();" name="smsl_pw" type="text" value="Password"> <input id="smsl_pw" onclick="changePass();" onblur="changeBack();" name="smsl_pw" type="text" value="Password">

希望它可以帮助某人

这是一个 function 用具有相同值的密码替换任何表单元素,知道它的 id:

function replaceWithPassword(id)
{
    var o = $('input#' + id + ', textarea#'+id + ', select#'+id);
    o.replaceWith('<input type="password" value="' + o.val() + '" id="' + id + '" />');
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM