2017-04-13 73 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

謝謝你,但它不工作的某些原因。謹慎闡述? – James

+0

@詹姆斯更新了答案。 –

+0

更好 - 現在它正確地在顯示和隱藏之間切換,但單擊隱藏後不會隱藏密碼。 – James

2

HTML:

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

的Javascript:

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

解決方案,以示對使用JavaScript密碼字段/隱藏切換按鈕。

<!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

請做出一些更改。

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>

+0

請儘快看到這個答案 – Keshav