Sometimes, we want to show or hide password on click a of button using JavaScript.
In this article, we’ll look at how to show or hide password on click a of button using JavaScript.
How to show or hide password on click a of button using JavaScript?
To show or hide password on click a of button using JavaScript, we can set the type
attribute of the input to to text
to show the password and set it to password
to hide it.
For instance, we write:
<input type='password'>
<button>
toggle show/hide
</button>
to add the password input and a button to show or hide the password in the input.
Then we write:
const input = document.querySelector('input')
const button = document.querySelector('button')
button.onclick = () => {
if (input.type === 'password') {
input.type = 'text'
} else {
input.type = 'password'
}
}
to select the input and button with querySelector
.
Next, we set button.onclick
to a function that checks if the type attribute of the input is password
with input.type === 'password'
.
If it’s true
, then we set input.type
to 'text'
to show the password.
Otherwise, we set input.type
to 'password'
to hide it.
Conclusion
To show or hide password on click a of button using JavaScript, we can set the type
attribute of the input to to text
to show the password and set it to password
to hide it.