
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Toggle Password Visibility in JavaScript
In this article, we are going to hide the password with ****. The password can be shown by toggling its visibility by using a button. We will be creating a JavaScript function that will display the hidden password when the toggle button is clicked.
Approach
On clicking the toggle button the JavaScript function to display the password will be rendered.
This will change the CSS property applied on the HTML input tag that will display the password.
We can toggle again to hide the password again.
Example
In the below example, we are toggling the visibility of the password using the checkboxcheckbox. On clicking the checkbox button the password will be displayed else it will be hidden.
# index.html
<!DOCTYPE html> <html> <head> <title> Toggle Password Visibility </title> </head> <body> <h2 style="color:green"> Welcome To Tutorials Point </h2> <div class="container"> <h3 class="mt-5 mb-5 text-center">Toggle password visibility</h3> <div class="form-group"> <label for="ipnPassword">Password</label> <div class="input-group mb-3"> <input type="password" class="form-control" id="ipnPassword"/> <div class="input-group-append"> <input type="checkbox" class="btn btn-outline-secondary" type="button" id="btnPassword">Show Password </button> </div> </div> </div> </div> </body> <script> // step 1 const ipnElement = document.querySelector('#ipnPassword') const btnElement = document.querySelector('#btnPassword') // step 2 btnElement.addEventListener('click', function() { // step 3 const currentType = ipnElement.getAttribute('type') // step 4 ipnElement.setAttribute('type',currentType === 'password' ? 'text' : 'password') }) </script> </html>
Output
Advertisements