Skip to the content.

How to toggle between password visibility

Pardeep
Jan 23, 2022

We use password fields in many signup/login forms in our applications. By default text in the password field is masked so we can’t see the actual text we have written.

Sometimes we need to check what actually we have entered as password.

Toggle Password

We can easily handle this functionality using very simple JS logic.

Follow the two steps below:

<div id="container">
  <!-- Password field -->
  Password: <input type="password" value="Toggle@123" id="password">

<!-- An element to toggle between password visibility -->
  <div>
    <input type="checkbox" onclick="togglePassword()">Show Password
  </div>
</div>

function togglePassword() {
  var x = document.getElementById("password");
  if (x.type === "password") {
    x.type = "text";
  } else {
    x.type = "password";
  }
}

Let’s understand the logic above.

If current input type is password we will change it to input type text and if input type is text, we will change it to input type password.

Try in CodePen

back