Home > OS >  Multiple ID In Javascript Function Not Working
Multiple ID In Javascript Function Not Working

Time:08-20

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();">

CodePudding user response:

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 ???

CodePudding user response:

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" >

  • Related