Press "Enter" to skip to content

JavaScript – Toggle Multiple Password Fields

Second exercise in Chris Ferdinandi‘s JavaScript Essentials course. Still feeling the hope, but a bit of disconcertedness crept in. This particular set of lessons and the resulting exercise ASSUME things one must already know about and/or be familiar with in JavaScript. I kinda knew about the things but didn’t have a good working understanding of them wholly. However, I was still able to follow his example of how to execute this exercise. Again, I was not able to summon how to do it on my own, but being able to follow and understand is what maintained the little feeling of hope.

So, in this exercise, you want to be able to check or uncheck a “show passwords” box and either show or mask ALL password fields on the page.

First step, setting up the variables. Now, for each of these, you are searching through the document for all fields with the parameters you’re going to set for your variable.

let passwords = document.querySelectorAll('[type="password"]');

This is setting the “passwords” variable. Like before, we’re using the “document.querySelector” method (I had to look up the terminology there to find out it’s a “method”) to find the thing(s) in the page which match what we want. In this case, the querySelector method has an “All” attached to it. document.querySelectorAll– What this will do is find ALL instances of the thing we’re gathering – which is items with a type of “password.” (Did that make sense?) You place the type information in square brackets: [type="password"]

let toggle = document.querySelector('#show-passwords');

This is defining the “toggle” variable to be the instance of finding the item with the ID of “show-passwords.” (Did THAT make sense??)

Okay, now that we have our variables defined, we can go ahead with making them do something – or rather make something happen – or allow something to be done. Quibble on your own time. The first thing we need to do, though, is create an “event listener” event – like in the last exercise – to “listen” for the “show passwords” box to be checked. This event listener will be attached to the “toggle” variable.

toggle.addEventListener('click', function () { });

This says that when the box is checked (when it “hears” the ‘click’), the function iterated here will be executed. (That function will be inside the curly brackets – nothing there yet.) The function in this case is going to be either show the passwords in the field as text or show them masked. It’s basically the same situation as the previous exercise except this time, it needs to apply to multiple fields. Therefore, we have to use a method that gathers all those fields and executes the function on each of them. Evidently, the way to do this is to use a “loop.” In this case, it will be what they call in JS Land a “for loop.” (Remember this goes inside the { } up in the Event Listener.)

for (let password of passwords) {
     if (toggle.checked) {
          password.type = 'text';
     }  else  {
          password.type = 'password';
     {
}

In this block, you are both defining the variable “password” (by using the word let) and integrating it into a group passwords. I think. Okay, hang on – let’s go through this. We already defined a variable for all items on the page which are “passwords.” In this case, we’re defining what a single one of those will be: “password” and telling what to do with each of them. ? Yes, I think that’s why we do that. So, this searches the whole page for everything which calls itself being part of the “passwords” group. It says, “You, single object, shall now be called a ‘password’!” Then we tell each of those parts of the “passwords” group to be a “text” type (which shows the password) or a “password” type (which masks the password).

Now, it’s important to realize something here. A lot of the words contained in this word casserole that is JavaScript are set items. Meaning, they’re built into JavaScript, so to speak.

let
document
.querySelector
.querySelectorAll
type
.addEventListener
click
function
.checked
.type

So, these are set things in JavaScript that will do something as soon as you plug them into the correct “formula.” (JavaScript is math with words, remember?) I’m sure as one goes along in the world of web dev, slogging through exercise after exercise (it’s really not mostly like slogging; I just like that word), some of these set features will become “set” in one’s memory banks. (I’ve heard there is quite the comprehensive list of these types of things over on MDN. Alternatively, you can find good JS info over on the W3 site, too.) Learn as you go; look up as you need. A good mantra for front-end web developers.

In closing, here is what the totality of the finished <script> code looks like (with appropriate comments included):

// Get the fields
let passwords = document.querySelectorAll('[type="password"]');
let toggle = document.querySelector("#show-passwords");

// listen for click events on the toggle
toggle.addEventListener("click", function () {
	// loop through each password field
	for (let password of passwords) {
		// if toggle is checked, change type to "text"
		// otherwise, change it back to "password"
		if (toggle.checked) {
			password.type = "text";
		} else {
			password.type = "password";
		}
	}
});

Happy coding!

Oh yeah, as a bit of an addendum here, there are multiple ways to achieve the same thing in JavaScript – just like in CSS. And, just like with CSS, if you ask in the community, you will get a bajillion different ways with everyone screaming about how theirs is the “best” way. Here is another way this could be done:

// get the fields
		let toggle = document.querySelector("#show-passwords");
		let currentPW = document.querySelector('#current-password');
		let newPW = document.querySelector('#new-password');

// listen for click events on the toggle
		toggle.addEventListener('click', function () {
			// if toggle is checked, change password type to "text"
			// if toggle is unchecked, leave it as type "password"
				if (toggle.checked) {
					currentPW.type = 'text';
					newPW.type = 'text';
				} else {
					currentPW.type = 'password';
					newPW.type = 'password';
				}
               });

Be First to Comment

Leave a Reply

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