0

I have a hidden form, due to two forms on the same page doing different submissions. The hidden form is then holding the password field that once entered it will show a section to the user, this part is all working with PHP and when the button is clicked. However, I have a addEventListener on the input field to listen out for when the user presses 'Enter'. Within the Event Listener I have declared the name of the button and then click() method to submit the form. But I run into the following error:

Uncaught TypeError: this.confirmPassowrd() is not a function?

JS

enterKey()
{
    document.querySelector('#password-confirm').addEventListener('keydown', function (e) {
       if (e.key === 'Enter') {
           this.confirmPassword();
       }
    });
}

confirmPassword()
{
    document.getElementById('confirm-password').click();
}

I'm not entirely sure what is happening, but if I put this as a normal function on the page where the html is, and call it it withing the enterKey() method it works fine. Any suggestions?

Kind regards,

James

Mikhail Vladimirov
  • 13,572
  • 1
  • 38
  • 40
Developer Jay
  • 953
  • 1
  • 10
  • 15

1 Answers1

1

You are losing the context of your class in the keydown event listener callback.

Try switching the function (e) you are passing in to an arrow function instead: e =>

An arrow function will preserve the lexical this of where it is created, whereas a function will take whatever this is handed to it when it is invoked. Therefore within your event listener function this no longer means "the instance of the class I am defined in".

UncleDave
  • 6,872
  • 1
  • 26
  • 44
  • thanks very much for this explanation, changing the function to an arrow function now works as expected. i will need to dig deeper in to the keyword this, I understand that it is used differently where ever it is used. – Developer Jay Mar 22 '19 at 17:00