当前位置:Gxlcms > JavaScript > 如何使用jQuery和JavaScript显示和隐藏密码

如何使用jQuery和JavaScript显示和隐藏密码

时间:2021-07-01 10:21:17 帮助过:12人阅读

下面本篇文章就给大家分别介绍使用jQuery和JavaScript显示和隐藏密码的方法,希望对大家有所帮助。

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

下面通过代码示例来介绍使用jQuery和JavaScript显示和隐藏密码的方法。【相关视频教程推荐:JavaScript教程、jQuery教程】

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

  1. <table>
  2. <tr>
  3. <td>Username : </td>
  4. <td><input type='text' id='username' ></td>
  5. </tr>
  6. <tr>
  7. <td>Password : </td>
  8. <td><input type='password' id='password' >&nbsp;
  9. <input type='checkbox' id='toggle' value='0' onchange='togglePassword(this);'>&nbsp; <span id='toggleText'>Show</span></td>
  10. </tr>
  11. <tr>
  12. <td>&nbsp;</td>
  13. <td><input type='button' id='but_reg' value='Sign Up' ></td>
  14. </tr>
  15. </table>

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

1、使用JavaScript实现

  1. <script type="text/javascript">
  2. function togglePassword(el){
  3. // Checked State
  4. var checked = el.checked;
  5. if(checked){
  6. // Changing type attribute
  7. document.getElementById("password").type = 'text';
  8. // Change the Text
  9. document.getElementById("toggleText").textContent= "Hide";
  10. }else{
  11. // Changing type attribute
  12. document.getElementById("password").type = 'password';
  13. // Change the Text
  14. document.getElementById("toggleText").textContent= "Show";
  15. }
  16. }
  17. </script>

说明:

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

效果图:

1.gif

2、使用jQuery实现

导入jQuery库

  1. <script type="text/javascript" src="jquery.min.js" ></script>

使用jQuery的attr()方法更改input元素的type属性。

  1. <script type="text/javascript">
  2. $(document).ready(function(){
  3. $("#toggle").change(function(){
  4. // Check the checkbox state
  5. if($(this).is(':checked')){
  6. // Changing type attribute
  7. $("#password").attr("type","text");
  8. // Change the Text
  9. $("#toggleText").text("隐藏密码");
  10. }else{
  11. // Changing type attribute
  12. $("#password").attr("type","password");
  13. // Change the Text
  14. $("#toggleText").text("显示密码");
  15. }
  16. });
  17. });
  18. </script>

输出:

2.gif

以上就是本篇文章的全部内容,希望能对大家的学习有所帮助。更多精彩内容大家可以关注Gxl网相关教程栏目!!!

以上就是如何使用jQuery和JavaScript显示和隐藏密码的详细内容,更多请关注Gxl网其它相关文章!

人气教程排行