Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Show/hide password onClick of button using Javascript only

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>
like image 974
user0428 Avatar asked Jul 04 '15 19:07

user0428


People also ask

How do I make my HTML password not visible?

</div> <div class="col-md-6"> <div class="form-group"> <input type="password" class="form-control" placeholder="Confirm Password" >

What is alternative for onclick?

You should use addEventListener() instead."


2 Answers

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>
like image 170
dfsq Avatar answered Oct 12 '22 12:10

dfsq


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>
like image 37
Ameen Ra'is Avatar answered Oct 12 '22 11:10

Ameen Ra'is