Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
570 views
in Technique[技术] by (71.8m points)

html - 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>
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...