0

I am trying to toggle the password on two fields with different ids using one JavaScript code but it isn't working.

One field works fine but the other doesn't respond, I have tried different solutions but I am not getting it right.

Any help will be appreciated.

See code below;

const togglePassword = document.querySelectorAll("#togglePassword, #togglePassword23");
        const password = document.querySelectorAll("#input2, #signup3");
        

        togglePassword.addEventListener("click", function toggle() {
            // toggle the type attribute
const type = password.getAttribute("type") === "password" ? "text" : "password";
            password.setAttribute("type", type);
            
            // toggle the icon
            this.classList.toggle("bi-eye");
        });
<input type="password" id="input2" autocomplete="new-password"><br/>
<input id="togglePassword" type="button" value="Toggle password 1" onclick="toggle();">
      <br/> <br/>
      
<input type="password" id="signup3" autocomplete="new-password"><br/>
<input id="togglePassword23" type="button" value="Toggle password 2" onclick="toggle();">

2 Answers2

1

You can find more details in the docs. In a nutshell - it returns an element object representing the first element in the document that matches the specified set of CSS selectors, or null is returned if there are no matches.

If you need a list of all elements matching the specified selectors, you should use querySelectorAll() instead.

p.s. Also, there is a typo in this line (I guess):

const password = document.querySelector("#input2, #input2"); // input2 input2 ???
ikos23
  • 4,879
  • 10
  • 41
  • 60
  • I have edited my question with the solutions suggested by you, Andy, and ikos23 and it didn't solve the problem. – Hippobrainz Aug 19 '22 at 17:34
  • @BABOSAMMONG now your question is a dupe of https://stackoverflow.com/questions/54937271/why-do-i-get-undefined-when-i-change-from-queryselector-to-queryselectorall – James Aug 19 '22 at 18:31
0

This is a working version of somewhat what you are trying to do. Should at least give you an idea of what was wrong with what you were trying:

const togglePassword = document.querySelectorAll("#togglePassword1, #togglePassword2");
const password = document.querySelectorAll("#input2, #input3");
        
togglePassword.forEach(function(item, index){
  item.addEventListener("click", function toggle() {
      // toggle the type attribute
      const type = password[index].getAttribute("type") === "password" ? "text" : "password";
      password[index].setAttribute("type", type);
    });
});
<input type="password" id="input2" autocomplete="new-password"><br/>
<input id="togglePassword1" type="button" value="Toggle password 1" >
<br/> <br/>
<input type="password" id="input3" autocomplete="new-password"><br/>
<input id="togglePassword2" type="button" value="Toggle password 2" >
Laslos
  • 340
  • 1
  • 7
  • 19