温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

使用jQuery和JavaScript显示和隐藏密码的方法

发布时间:2020-08-27 14:47:38 来源:亿速云 阅读:186 作者:小新 栏目:web开发

这篇文章将为大家详细讲解有关使用jQuery和JavaScript显示和隐藏密码的方法,小编觉得挺实用的,因此分享给大家做个参考,希望大家阅读完这篇文章后可以有所收获。

为了账户的安全,我们总是会把密码设置的很复杂;当输入密码时,因为密码的不显示,我们不知道输的是对还是错,有可能导致身份验证错误。因而,现在的网站允许用户通过切换来查看密码字段中的隐藏文本。

下面通过代码示例来介绍使用jQuery和JavaScript显示和隐藏密码的方法。

HTML代码:首先我们需要创建了基本表单布局

<table>
 <tr>
  <td>Username : </td>
  <td><input type='text' id='username' ></td>
 </tr>
 <tr>
  <td>Password : </td>
  <td><input type='password' id='password' >&nbsp;
     <input type='checkbox' id='toggle' value='0' onchange='togglePassword(this);'>&nbsp; <span id='toggleText'>Show</span></td>
 </tr>
 <tr>
  <td>&nbsp;</td>
  <td><input type='button' id='but_reg' value='Sign Up' ></td>
 </tr>
</table>

说明:在复选框元素上附加onchange="togglePassword()"事件,调用js代码,实现切换密码的显示(或隐藏)

1、使用JavaScript实现

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

说明:

检查复选框的状态是否为选中,选中则input框的type属性切换为text,未选中则type属性保持为password。

效果图:

使用jQuery和JavaScript显示和隐藏密码的方法

2、使用jQuery实现

导入jQuery库

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

输出:

使用jQuery和JavaScript显示和隐藏密码的方法

关于使用jQuery和JavaScript显示和隐藏密码的方法就分享到这里了,希望以上内容可以对大家有一定的帮助,可以学到更多知识。如果觉得文章不错,可以把它分享出去让更多的人看到。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI