Show/hide password onClick of button using Javascript only

后端 未结 13 895
孤城傲影
孤城傲影 2020-12-08 22:47

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

相关标签:
13条回答
  • 2020-12-08 23:14

    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>

    0 讨论(0)
提交回复
热议问题