• Post category:JavaScript
  • Reading time:4 mins read

Today, we’ll explain to you how to show and hide password using jQuery.

In this toggle or show/hide password functionality, you can see the password during writing. Here we check the input field type, if there is a password, we will change it to text. If it is a text, we will change it to password using jQuery.

Here, we will create the HTML form where we have taken the password field as shown below. Write the following code and run to check the output.

index.html
<!DOCTYPE html>
<html>

<head>
  <title>Show and Hide password field text using jQuery - Code Premix</title>
  <!-- CSS -->
  <link href='https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css' rel='stylesheet' type='text/css'>
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">

  <!-- JS -->
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>

  <style>
    #password {
      border-top-right-radius: 0;
      border-bottom-right-radius: 0;
      border-right: 0;
    }

    #password:focus {
      box-shadow: none;
      border-color: #ced4da;
    }

    #toggle-password {
      border: 1px solid #ced4da;
      line-height: 36px;
      border-left: 0;
      border-radius: 3px;
      border-top-left-radius: 0;
      border-bottom-left-radius: 0;
      width: 30px;
      cursor: pointer;
    }
  </style>
</head>

<body>
  <div class="container">
    <div class="col-md-8 mt-4 ">
      <h5>Show and Hide password using jQuery - <a href="https://codepremix.com" target="_blank" rel="noopener noreferrer">Code Premix</a></h5>
      <form class="form-inline mt-3">
        <div class="form-group mb-2">
          <input type="password" class="form-control" id="password" /><span id="toggle-password"
            class="fa fa-fw fa-eye pass-icon"></span>
        </div>
      </form>
    </div>
  </div>

  <script>
    $(document).on('click', '#toggle-password', function () {
      $(this).toggleClass("fa-eye fa-eye-slash");
      var input = $("#password");
      input.attr('type') === 'password' ? input.attr('type', 'text') : input.attr('type', 'password')
    });
  </script>
</body>

</html>

Output

Output - How to show and hide Password using jQuery - Code Premix
Output – How to show and hide Password using jQuery – Code Premix

That’s it for today.
Thank you for reading. Happy Coding..!!

Leave a Reply