如何使用复选框更改文本框文本模式

时间:2016-08-01 17:19:04

标签: javascript asp.net

如果取消选中该复选框,如何将文本框文本模式更改为密码,然后如果未选中文本框文本模式=文本,则设置textmode = password 使用javascript?

我试过这段代码

 function test() {
     if ($('#TBPASS12').get(0).type = 'text') {
         document.getElementById('<%= TBPASS12.ClientID %>').type = 'password';
     }
     else if ($('#TBPASS12').get(0).type = 'password') {
         document.getElementById('<%= TBPASS12.ClientID %>').type = 'text';
     }        
 }

2 个答案:

答案 0 :(得分:0)

javascript中的文字模式为read only。所以你不能改变js中的类型。 你只能做一件事,动态创建文本框并setattribute给他们并用以前的

替换

试试这个,

$(function(){
  var inp = document.getElementById("in");
  if(inp.type == 'text'){  
    var newIn = document.createElement('input'); 
    newIn.setAttribute('type', 'password');
    newIn.setAttribute('id', inp.getAttribute('id'));
    newIn.setAttribute('name', inp.getAttribute('name'));
    inp.parentNode.replaceChild(newIn, inp);
    newIn.focus();
  }
});
<!DOCTYPE html>
<html>

  <head>
    <meta charset="utf-8" />
    <title></title>
    <link href="style.css" rel="stylesheet" />
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.0.0/jquery.js" data-semver="3.0.0" data-require="jquery"></script>
    <script src="script.js"></script>
  </head>

  <body> 
   <input id="in" type="text"/>
  </body>

</html>

答案 1 :(得分:0)

您想透露密码吗?正如其他人所说,文本模式是只读的,但你可以做一些事情。

(编辑:片段中曾经有一个小错误,但我修复它以反映无错误的小提琴!该代码片段成功运行)

希望这有帮助

var x= document.createElement("INPUT");
var y= document.createElement("INPUT");
x.setAttribute("type", "password");
x.id = "<%= TBPASS12.ClientID %>";
x.className = "password1";
x.value ="";
document.body.appendChild(x);

var passwords = document.getElementsByClassName("password1");
for (var i = 0; i < passwords.length; i++) {
   passwords[i].addEventListener('keydown', checkEnter, false);
}

function checkEnter (e){
  if (e.keyCode == 13) {
    if ((".password1").value !== null) {
      y.setAttribute("type", "text");
      y.id = "value";
      y.value = x.value;
      y.style.display="block";
      document.body.appendChild(y);
     
    }
  }
}
input[type="password"] {
  background: lightblue;
  width: 100px;
  height: 20px;
  display: block;
}

input[type="text"] {
  display:none;
  background: lightgreen;
  width: 100px;
  height: 20px;
  display: block;
}
<body>
</body>