For input types of 'password', browsers mark the user's input (typically by replacing the characters with asterisk '*'or dot '.') for security reasons. However, the user might want to confirm that his input in plain text, so there is the need for an option to toggle the password visibility.
Step 1: Create the HTML input tag [type= 'password']
<input type='password' id='password' />
<p>
Show Password
<input type='checkbox' id='checkbox' />
</p>
Step 2: Store selectors (Javascript)
const myInput = document.querySelector("#password");
const checkbox = document.querySelector("#checkbox");
Step 3: Toggle visibility function
This checks toggles the input tag (myInput) type between type password and type text
const toggleVisibility = () => {
if (myInput.type === "password") {
myInput.type = "text";
} else {
myInput.type = "password";
}
};
Step 4: Assign this function to the checkbox onchange event
checkbox.addEventListener("change", toggleVisibility);
Checkout this codepen for the working code.
Top comments (0)