I am using 2 same id's in my HTML file that connect to my JavaScript file and I know this brings up issues because you can't use 2 id's with the same name, but I wanted to see if there's a short way around this?
HTML code below
<div >
<input type="password" required="" id="id_password">
<i id="togglePassword"></i>
<span></span>
<label>Password</label>
</div>
<div >
<input type="password" required="" id="id_password">
<i id="togglePassword"></i>
<span></span>
<label>Confirm Password</label>
Below is my JavaScript code
const togglePassword1 = document.querySelector('#togglePassword');
const password = document.querySelector('#id_password');
togglePassword.addEventListener('click', function (e){
// toggle the type attribute
const type = password.getAttribute('type') === 'password' ? 'text' : 'password';
password.setAttribute('type', type);
// toggle the eye slash icon
this.classList.toggle('fa-eye-slash');
});
CodePudding user response:
You never ever ever want to use duplicate ids, you could still differentiate between the two if you do
querySelectorAll("#id_password")
and then grab index 0 or index 1 according to your correct variable, again NOT RECOMMENDED don't use duplicate ids.
CodePudding user response:
Here is a simple way of doing it without IDs:
document.body.addEventListener('click', function (e){
if(e.target.classList.contains("far")){
const inp=e.target.previousElementSibling;
inp.type=inp.type=="text"?"password":"text";
}
});
<div >
<input type="password" required="" name="pw1">
<i >👁</i>
<span></span>
<label>Password</label>
</div>
<div >
<input type="password" required="" name="pw2">
<i >👁</i>
<span></span>
<label>Confirm Password</label>