In HTML, when you set the type of an input field as text, it makes the text in the input field visible but if you set the type to password, then that text will be masked with dots.
In the following example, we have one password field and a checkbox right next to it. Depending upon the state of the checkbox, we will mask or unmask the password. Please have a look over the code example and the steps given below.
HTML & CSS
We have 3 elements in the HTML file (div, input, and label). The div element is just a wrapper for the rest of the elements.
One of the input elements is of type checkbox and has text “Show” as a label.
We have done some basic styling using CSS and added the link to our style.css stylesheet inside the head element.
padding: 10px 20px;
We have selected both the input elements using the document.querySelector() method and stored them in the input and checkbox variables.
We have attached a click event listener to the checkbox input element.
In the event handler function, we are using the if else statement and checked property of the checkbox input element to verify whether the checkbox is checked or not. The checked property returns a Boolean value and depending upon that, we are changing the type of the input using type property. If checked, we will set the type to text. Otherwise, we will set it to password.