Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Change type of two input fields independently of each other

I have two input fields and when you click on the eye next to it, only the input field next to it should be changed from type password to text.

The first one is working but the second one doesn’t changes at all.

let passwordInputEye = document.querySelector('#password');
let eye = document.querySelector('#eye');
eye.addEventListener('click', function() {
    this.classList.toggle('fa-eye-slash');
    const type = passwordInputEye.getAttribute('type') === 'password' ? 'text' : 'password';
    passwordInputEye.setAttribute('type', type);
})
.fa-eye {
    position: absolute;
    font-size: 24px;
}
.fa-eye-slash {
    
}
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.1.1/css/all.min.css">

<div>
  <input class="input-field-register" id="password" type="password" placeholder="Passwort" maxlength="16">
  <i class="fa-solid fa-eye" id="eye"></i>
</div>

<div>
  <input class="input-field-login" id="password" type="password" placeholder="Passwort" maxlength="16">
  <i class="fa-solid fa-eye" id="eye"></i>
</div>

I tried to change the id’s to classes but that doesn’t seem to work either.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

you have to use class if you want the code to be triggered, register by iterating each class using querySelectorAll.
I hope its help

let eye = document.querySelectorAll('.eye');
let pass = document.querySelectorAll('.password');
eye.forEach(function (v, i) {
    v.addEventListener('click', function () {
        this.classList.toggle('fa-eye-slash');
        const type = pass[i].getAttribute('type') === 'password' ? 'text' : 'password';
        console.log(pass[i], i)
        pass[i].setAttribute('type', type);
    })
});
.fa-eye {
    position: absolute;
    font-size: 24px;
}
.fa-eye-slash {
    
}
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.1.1/css/all.min.css">

<div>
  <input class="input-field-login password" type="password" placeholder="Passwort" maxlength="16">
  <i class="fa-solid fa-eye eye"></i>
</div>

<div>
  <input class="input-field-login password"  type="password" placeholder="Passwort" maxlength="16">
  <i class="fa-solid fa-eye eye"></i>
</div>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading