Show/hide password onClick of button using Javascript only

后端 未结 13 955
孤城傲影
孤城傲影 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:09

    You don't need to maintain one extra "pwShown" variable to decide whether to show text or hide it. All you need to do is to examine "type" attribute of "pwd" element as below :

    Working Example

    JavaScript :

    document.getElementById("eye").addEventListener("click", function(e){
            var pwd = document.getElementById("pwd");
            if(pwd.getAttribute("type")=="password"){
                pwd.setAttribute("type","text");
            } else {
                pwd.setAttribute("type","password");
            }
        });
    

    HTML :

    
            
    

提交回复
热议问题