您好,登錄后才能下訂單哦!
這篇文章將為大家詳細(xì)講解有關(guān)使用jQuery和JavaScript顯示和隱藏密碼的方法,小編覺得挺實(shí)用的,因此分享給大家做個(gè)參考,希望大家閱讀完這篇文章后可以有所收獲。
為了賬戶的安全,我們總是會(huì)把密碼設(shè)置的很復(fù)雜;當(dāng)輸入密碼時(shí),因?yàn)槊艽a的不顯示,我們不知道輸?shù)氖菍?duì)還是錯(cuò),有可能導(dǎo)致身份驗(yàn)證錯(cuò)誤。因而,現(xiàn)在的網(wǎng)站允許用戶通過切換來(lái)查看密碼字段中的隱藏文本。
下面通過代碼示例來(lái)介紹使用jQuery和JavaScript顯示和隱藏密碼的方法。
HTML代碼:首先我們需要?jiǎng)?chuàng)建了基本表單布局
<table> <tr> <td>Username : </td> <td><input type='text' id='username' ></td> </tr> <tr> <td>Password : </td> <td><input type='password' id='password' > <input type='checkbox' id='toggle' value='0' onchange='togglePassword(this);'> <span id='toggleText'>Show</span></td> </tr> <tr> <td> </td> <td><input type='button' id='but_reg' value='Sign Up' ></td> </tr> </table>
說明:在復(fù)選框元素上附加onchange="togglePassword()"事件,調(diào)用js代碼,實(shí)現(xiàn)切換密碼的顯示(或隱藏)
1、使用JavaScript實(shí)現(xiàn)
<script type="text/javascript"> function togglePassword(el){ // Checked State var checked = el.checked; if(checked){ // Changing type attribute document.getElementById("password").type = 'text'; // Change the Text document.getElementById("toggleText").textContent= "Hide"; }else{ // Changing type attribute document.getElementById("password").type = 'password'; // Change the Text document.getElementById("toggleText").textContent= "Show"; } } </script>
說明:
檢查復(fù)選框的狀態(tài)是否為選中,選中則input框的type屬性切換為text,未選中則type屬性保持為password。
效果圖:
2、使用jQuery實(shí)現(xiàn)
導(dǎo)入jQuery庫(kù)
<script type="text/javascript" src="jquery.min.js" ></script>
使用jQuery的attr()方法更改input元素的type屬性。
<script type="text/javascript"> $(document).ready(function(){ $("#toggle").change(function(){ // Check the checkbox state if($(this).is(':checked')){ // Changing type attribute $("#password").attr("type","text"); // Change the Text $("#toggleText").text("隱藏密碼"); }else{ // Changing type attribute $("#password").attr("type","password"); // Change the Text $("#toggleText").text("顯示密碼"); } }); }); </script>
輸出:
關(guān)于使用jQuery和JavaScript顯示和隱藏密碼的方法就分享到這里了,希望以上內(nèi)容可以對(duì)大家有一定的幫助,可以學(xué)到更多知識(shí)。如果覺得文章不錯(cuò),可以把它分享出去讓更多的人看到。
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。