I try to toggle classes of eye and eye-slash in password (show/hide) input field, but it is not working
please fix if anyone knows, thank you.
and can anyone change within this code is appreciated. we need this code to get working .
<script>
const togglePassword = document
.querySelector('#togglePassword');
const password = document.querySelector('#password');
togglePassword.addEventListener('click', () => {
// Toggle the type attribute using
// getAttribure() method
const type = password
.getAttribute('type') === 'password' ?
'text' : 'password';
password.setAttribute('type', type);
// Toggle the eye and bi-eye icon
this.classList.toggle('bi-eye');
});
</script>
<p>
<label>Password:</label>
<input type="password"
name="password" id="password" />
<i
id="togglePassword"></i>
</p>
CodePudding user response:
Console log shows that this
is not defined. Your code is mixing jQuery and javascript syntaxes apparently. Consider one of the following changes:
- Change the event listener to jQuery, e.g.
$(togglePassword).on('click', function() { ... });
- Change the toggle line to
event.target.classList.toggle('bi-eye');
- See https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener#specifying_this_using_bind for the javascript way to define this. jQuery event binding noted in 1 does this for you.
CodePudding user response:
<script>
const togglePassword = document
.querySelector('#togglePassword');
const password = document.querySelector('#password');
togglePassword.addEventListener('click', function (e) => {
// Toggle the type attribute using
// getAttribure() method
const type = password
.getAttribute('type') === 'password' ?
'text' : 'password';
password.setAttribute('type', type);
// Toggle the eye and bi-eye icon
this.classList.toggle('bi-eye');
});
</script>
<p>
<label>Password:</label>
<input type="password"
name="password" id="password" />
<i
id="togglePassword"></i>
</p>