Show and hide password of input box in JavaScript

If we create an HTML input field of type password then we can see that we are not able to see the password. We will see something like “********” instead of the password.

Well, on many of the website we may find that it has a toggle option which let us show/hide the password. Did you ever think how it works?

How to generate a random password in JavaScript?

Guess The Number Game Using JavaScript

Now in this post, we are going to create our HTML input with type password. After that using JavaScript, we will change the type of the input field. When the type of the input field will change from password to text, we will able to see the value in the password type input field. This is because text type HTML input field is visible and we are changing the type of the input from password to text.

Below is our HTML code:

Password: <input type="password" value="dummy1234" id="password">
<input type="checkbox" id="show_password">Show Password

In the above HTML code, we have created an input field of type password. Next, to the password field, we have added a checkbox which will toggle the password visibility of the input.

Now below is our JavaScript code that will add the functionality to our checkbox and input field:

document.getElementById("show_password").addEventListener("click", function(){
    var pw = document.getElementById("password");
    if (pw.type == "password") {
        pw.type = "text";
    } else {
        pw.type = "password";


With our JavaScript code, we have added click event listener to the checkbox. After that, we have checked the password input field type. if the type of the input is “password”, then it will change the type into text and if the type is text, it will then change that into password¬†type.

Stop form submission using JavaScript preventDefault() Event Method

Leave a Reply

Your email address will not be published. Required fields are marked *