Show and hide password using JavaScript
We will show you how to Hide/Show passwords using JavaScript. While filling up a form, there comes a situation where we type a password and want to see what we have typed till now. To see that, there is a checkbox click on which makes the characters visible. In this article, we will add the toggle password feature using JavaScript.
Example:
Password is geeksforgeeks.
So, on typing it will show like this *************
And on clicking the checkbox it will show the characters: geeksforgeeks.
Approach
- HTML Structure:
- HTML5 structure with meta tags and a title.
- Instructions to click on a checkbox to show/hide the password.
- Password input field and a checkbox are included.
- Password Input:
- Input field of type password (
id="typepass"
).
- The initial value is set to “geeksforgeeks.”
- Show Password Checkbox:
- Checkbox with an
onclick
event calling the Toggle()
function.
- JavaScript Function (
Toggle()
):
- Function toggles password visibility.
- Retrieves password input element and changes its type.
- Toggles between “password” and “text” based on the current type.
- Interaction:
- Users clicking the checkbox triggers the
Toggle()
function.
- Dynamically changes the password input type for showing/hiding the password.
Example: This example shows the implementation of the above-explained approach.
HTML
<!DOCTYPE html>
< html lang = "en" >
< head >
< meta charset = "UTF-8" >
< meta http-equiv = "X-UA-Compatible"
content = "IE=edge" >
< meta name = "viewport"
content = "width=device-width, initial-scale=1.0" >
< title >
Show and hide password using JavaScript
</ title >
</ head >
< body >
< strong >
< p >Click on the checkbox to show
or hide password:
</ p >
</ strong >
< strong >Password</ strong >:
< input type = "password" value = "geeksforgeeks"
id = "typepass" >
< input type = "checkbox" onclick = "Toggle()" >
< strong >Show Password</ strong >
< script >
// Change the type of input to password or text
function Toggle() {
let temp = document.getElementById("typepass");
if (temp.type === "password") {
temp.type = "text";
}
else {
temp.type = "password";
}
}
</ script >
</ body >
</ html >
|
Output:
Show and hide passwords using JavaScript
Last Updated :
16 Jan, 2024
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...