1

I need to add a password toggle visibility to the password input fields in magento 2 checkout pages and I can't find a way to work with knockout js.

I am using only javscript to add a span with a click event that changes the input field type from password to text, and it works on all inputs except the ones from the checkout pages.

I want to avoid making any changes to xml or template files, I was looking for a solution to do this only with javascript.

This is the code I have in my module:

require(['jquery'], function($) {$(function() {

    var passwordInput = document.querySelectorAll('input[type="password"]');

    passwordInput.forEach(function(selectedInput) {
       var passwordToggle = document.createElement('span');
       passwordToggle.setAttribute('class', 'show-password');

        selectedInput.parentNode.appendChild(passwordToggle);

        passwordToggle.addEventListener('click', function() {
            if (selectedInput.type === "password") {
                selectedInput.type = "text";
                this.classList.add('visible');
            } else {
                selectedInput.type = "password";
                this.classList.remove('visible');
            }
        });
    });

});});
Aref
  • 746
  • 10
  • 27
  • I can see you are calling this code on `document ready`, are you sure that the password elements exist at that point? In case they were created dynamically during page lifecycle, then the `passwordInput` array would be empty. – Piotr Wicijowski May 22 '19 at 19:08
  • No, the password input is loaded with knockout js, that's the issue. I'm not really sure how that works. – Chiru Alexandru May 23 '19 at 11:28
  • If you're using knockout, you shouldn't use eventlisteners and jquery. They don't play well well together. – Will Jenkins May 23 '19 at 15:48

0 Answers0