Reputation: 9
I have been working on a project that requires me to toggle between showing and hiding the password in a password field.
The JS code I came up with is:
<script>
function text(item) {
if (document.getElementById('password').type = "password") {
document.getElementById('password').type = "text";
} else {
document.getElementById('password').type = "password";
}
}
</script>
<input type="checkbox" id="logon-show-password" name="showpassword" class="tickable" onclick="text(this)">
<input type="password" id="password" />
For some reason, it works just fine when toggling between password -> text, but fails to do the opposite.
What am I doing wrong?
Upvotes: 0
Views: 563
Reputation: 12478
You are missing an =
in the if condition
if(document.getElementById('password').type="password"){
^^^^
Should be
if(document.getElementById('password').type=="password"){
Otherwise it will assign the type password to the field and it will return true always
function text(item) {
if (document.getElementById('password').type == "password") {
document.getElementById('password').type = "text";
} else {
document.getElementById('password').type = "password";
}
}
<input type="checkbox" id="logon-show-password" name="showpassword" class="tickable" onclick="text(this)">
<input id="password" type="password" />
Upvotes: 1