我正在尝试将显示的输入文本的类型从文本更改为密码。它会改变我想要的类型,但显示的文本不会从可见变为不可见..
function changeType() {
var x = document.getElementById("Table").rows[1].cells;
var value = x[0].value;
if (x[0].type == "password") {
x[0].type = "text";
} else {
x[0].type = "password";
}
}
<table id="Table" class="table table-bordered table-dark table-striped table-hover">
<tr>
<th>website</th>
<th>username</th>
<th>
<input type="checkbox" onclick="changeType()"> password
</th>
</tr>
<td><input type="password" value="1234567" readonly="readonly"></td>
<td><input type="text" value="9876543" readonly="readonly"></td>
<td><input type="text" value="simpleTest" readonly="readonly"></td>
</table>
答案 0 :(得分:1)
您可以使用querySelector
在您自己的代码上轻松完成此操作,如下所示:
function changeType() {
var x = document.querySelector("input.password");
var value = x.value;
if (x.type === "password") {
x.type = "text";
} else {
x.type = "password";
}
}
<table id="Table" class="table table-bordered table-dark table-striped table-hover">
<tr>
<th>website</th>
<th>username</th>
<th>
<input type="checkbox" onclick="changeType()"> password
</th>
</tr>
<td><input type="password" class="password" value="1234567" readonly="readonly"></td>
<td><input type="text" value="9876543" readonly="readonly"></td>
<td><input type="text" value="simpleTest" readonly="readonly"></td>
</table>
我希望我一直很有用! :)
答案 1 :(得分:1)
评论中提到了HTML和JavaScript的问题:
<tr>
元素周围缺少<td>
。x
指的是表格单元格,而不是输入。在您的上下文中,我通过为每个元素提供自己的ID来简化 这样你就不需要遍历DOM了。
您可以在原始代码中使用内联onclick
方法
我已根据自己的喜好将其更改为addEventListener
。
function toggleType(input) {
input.type = (input.type == 'password') ?
'text' :
'password';
}
var pass_input = document.getElementById("pass_input");
var pass_toggle = document.getElementById('pass_toggle');
pass_toggle.addEventListener('change', function() {
toggleType(pass_input)
});
th {
text-align: left;
}
label {
cursor: pointer;
}
<table>
<thead>
<tr>
<th>website</th>
<th>username</th>
<th>
<label><input type="checkbox" id="pass_toggle"> password</label>
</th>
</tr>
</thead>
<tbody>
<tr>
<td><input type="text" value="simpleTest" readonly="readonly"></td>
<td><input type="text" value="9876543" readonly="readonly"></td>
<td><input type="password" id="pass_input" value="1234567" readonly="readonly"></td>
</tr>
</tbody>
</table>