javascripthtmlmultiple-instances

Multiple ID In Javascript Function Not Working


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


Solution

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