2017-04-13 4 views
1

양식 비밀번호 필드에 표시/숨기기 버튼을 구현해야하는 프로젝트에서 비밀번호를 일반 텍스트로 표시하고 별표 뒤에 숨기는 프로젝트를 진행하고 있습니다.Javascript 비밀번호 필드의 토글 버튼 표시/숨기기

지금까지 해낸 무엇 :

<script> 

function pass(){ document.getElementById('password').type="password"; } 
function text(){ document.getElementById('password').type="text"; } 

</script> 

그리고 버튼의 HTML 코드 :

<button class="ui-component__password-field__show-hide" type="button" 
onclick="text()">Show</button> 

그것은 암호를 보여주는로 전환 잘 작동하지만 내가 어떻게해야합니까 암호가 표시되면 버튼의 텍스트를 "숨기기"로 변경하고 pass() 함수를 실행하게 하시겠습니까?

답변

1
<button class="ui-component__password-field__show-hide" type="button" 
onclick="text(this)">Show</button> 


    function text(item){ 
    if(item.innerText=='Show'){ 
     item.innerText='Hide'; 
     document.getElementById('password').type="password"; 
    }else{ 
    item.innerText='Show'; 
    document.getElementById('password').type="text"; 
    } 


    } 
+0

function text() { var a=document.getElementById('password'); var b=document.getElementById('button'); if (a.type=="password"){ a.type = "text"; b.innerText = "Hide"; } else { a.type = "password"; b.innerText = "Show"; } }
<input type="password" id="password"> <button class="ui-component__password-field__show-hide" type="button" onclick="text()" id="button">Show</button>

감사합니다,하지만 어떤 이유로 작동하지 않습니다. 정교한 케어? – James

+0

@James가 답변을 업데이트했습니다. –

+0

더 좋음 - 이제는 표시 및 숨기기를 올바르게 전환하지만 숨기기를 클릭하면 암호를 숨기지 않습니다. – James

2

HTML :

<input type="password" id="password"> 
<button onclick="toggler(this)" type="button">Show</button> 

자바 스크립트 :

function toggler(e) { 
     if(e.innerHTML == 'Show') { 
      e.innerHTML = 'Hide' 
      document.getElementById('password').type="text"; 
     } else { 
      e.innerHTML = 'Show' 
      document.getElementById('password').type="password"; 
     } 
} 

이 작업 예제를 확인하시기 바랍니다. 나는이 자바 스크립트를 사용하여 암호 필드/숨기기 토글 버튼을 보여주기 위해 당신에게

https://jsfiddle.net/ra8ot13y/

0

솔루션을 도움이되기를 바랍니다.

<!DOCTYPE html> 
<html> 
<head> 
<title>Password-Show/Hide</title> 
<script type="text/javascript"> 
//alert("hi"); 
function toggle(){ 
    alert("hello"); 
    var button = document.getElementById("show_hide").innerHTML; 
    var pass = document.getElementById("password"); 
    if(button == "Show Password"){ 
     pass.setAttribute("type","text"); 
     document.getElementById("show_hide").innerHTML = 'Hide Password'; 
    } 
    else{ 
     pass.setAttribute("type","password"); 
     document.getElementById("show_hide").innerHTML = "Show Password"; 
    } 

} 
window.addEventListener("load",function(){ 
    var sh = document.getElementById("show_hide"); 
    sh.addEventListener("click",toggle); 
}); 
</script> 
</head> 
<body> 
<input type="password" name="password" id="password" placeholder="Password" /> 
<button id="show_hide" >Show Password</button> 
</body> 
</html> 
0

일부 내용을 변경하십시오.

+0

제발 가능한 한 빨리이 답변을 참조하십시오 – Keshav