I want to create password toggle function when clicked on the eye icon using Javascript only. I have written code for it but it works only to show the password text and not the other way round. Can someone see the logic error in the code below.
function show() {
var p = document.getElementById('pwd');
p.setAttribute('type', 'text');
}
function hide() {
var p = document.getElementById('pwd');
p.setAttribute('type', 'password');
}
function showHide() {
var pwShown = 0;
document.getElementById("eye").addEventListener("click", function() {
if (pwShown == 0) {
pwShown = 1;
show();
} else {
pwShow = 0;
hide();
}
}, false);
}
<input type="password" placeholder="Password" id="pwd" class="masked" name="password" />
<button type="button" onclick="showHide()" id="eye">
<img src="eye.png" alt="eye"/>
</button>
</div> <div class="col-md-6"> <div class="form-group"> <input type="password" class="form-control" placeholder="Confirm Password" >
You should use addEventListener() instead."
You are binding click event every time you click a button. You don't want multiple event handlers. Plus you are redefining var pwShown = 0
on every click so you can never revert input state (pwShown
stays the same).
Remove onclick attribute and bind click event with addEventListener:
function show() {
var p = document.getElementById('pwd');
p.setAttribute('type', 'text');
}
function hide() {
var p = document.getElementById('pwd');
p.setAttribute('type', 'password');
}
var pwShown = 0;
document.getElementById("eye").addEventListener("click", function () {
if (pwShown == 0) {
pwShown = 1;
show();
} else {
pwShown = 0;
hide();
}
}, false);
<input type="password" placeholder="Password" id="pwd" class="masked" name="password" />
<button type="button" id="eye">
<img src="https://cdn0.iconfinder.com/data/icons/feather/96/eye-16.png" alt="eye" />
</button>
The easiest way is using a button with an onclick
attribute that toggles the type of the input.
<input type="password" id="password" value="myPassword"/>
<button onclick="if (password.type == 'text') password.type = 'password';
else password.type = 'text';">toggle</button>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With