Home > Back-end >  Unable to toggle classes for eye icon and eye slash icon using jquery
Unable to toggle classes for eye icon and eye slash icon using jquery

Time:01-25

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:

  1. Change the event listener to jQuery, e.g. $(togglePassword).on('click', function() { ... });
  2. Change the toggle line to event.target.classList.toggle('bi-eye');
  3. 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>
  • Related