0

I have a question in react/JavaScript that when I press Tab on the keyboard, I need the Enter key to be triggered or active, so any idea how can I do it.

Sam RQ
  • 25
  • 1
  • 7

1 Answers1

2

Although I'm not sure what you're motivation for this behavior is, your logic is even possible with Vanilla JS:

Minimal example for your use case:

  • Click into the input field
  • Now press tab
  • You will see an alert that tab was pressed
  • Immediately after, you will see that enter was pressed as well (programmatically)

let element = document.querySelector('input');
element.onkeydown = e => {
  alert('key pressed: ' + e.key);
  if (e.key === 'Tab') {
    element.dispatchEvent(
      new KeyboardEvent('keydown', {
        'key': 'enter'
      }));
  }
}
<input/>
gru
  • 2,319
  • 6
  • 24
  • 39
  • 1
    While this link may answer the question, it is better to include the essential parts of the answer here and provide the link for reference. Link-only answers can become invalid if the linked page changes. - [From Review](/review/low-quality-posts/30837408) – Jamiec Jan 17 '22 at 17:00
  • Thanks for your feedback, I added a working minimal example. – gru Jan 17 '22 at 17:15