skip to Main Content

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 class="bi bi-eye-slash"
                id="togglePassword"></i>
        </p>

2

Answers


  1. Chosen as BEST ANSWER
    <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 class="bi bi-eye-slash"
                    id="togglePassword"></i>
            </p>
    

  2. 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.
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search