Show and Hide Password Field Text with jQuery and JavaScript

Password field by default doesn’t show any visible text other than the symbol.

Some websites allow the user to view the hidden text in the password field by toggling.

For this, they provide an element e.g. checkbox or a button when it gets clicked then the password element value is been visible on the screen and reset to default view when it again gets clicked.

In this tutorial, I show how you can implement this functionality with jQuery and JavaScript.

Show and Hide Password Field Text with jQuery and JavaScript


Contents

  1. With JavaScript
  2. With jQuery
  3. Demo
  4. Conclusion

1. With JavaScript

Created a basic form layout here, attach onchange="togglePassword()" event on the checkbox element.

HTML

<table>
 <tr>
  <td>Name : </td>
  <td><input type='text' id='name' ></td>
 </tr>
 <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>

JavaScript

Check the state of the checkbox if it’s being checked then switch the type attribute of the password element to text otherwise to the password.

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

2. With jQuery

Change type attribute of the input element with attr() method.

Completed Code

$(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("Hide");
  }else{
   // Changing type attribute
   $("#password").attr("type","password");
  
   // Change the Text
   $("#toggleText").text("Show");
  }
 
 });
});

3. Demo

View Demo


4. Conclusion

You can use this feature as a replacement for re-type or confirm password field from your sign-up form.

It is a great feature that allows the user to view and verify its password but it is a little risky in terms of security if your password is being exposed.

If you found this tutorial helpful then don't forget to share.