Kanagambigai Murugan
Kanagambigai Murugan

Reputation: 90

Dispatch event on an input element while pressing tab key is not working in JavaScript

I am trying to dispatch tab key Press event pro grammatically on a button click. When the button is clicked, I provided focus for the first input and dispatched key press event with tab key and try to focus the second input. But unfortunately this is not working.

document.getElementById('btn').addEventListener('click', function() {
  const input = document.getElementsByTagName('input')[0];
  input.focus();
  alert('Input 1 focused');
  input.dispatchEvent(
    new KeyboardEvent('keypress', {
      key: 'tab',
      code: 'tab',
      keyCode: 9
    })
  );

});
<button id="btn">click</button>
<input id="default" tabindex="0" />
<br />
<br />
<br />
<input id="default1" tabindex="0" />

I expect upon button click, the second input should be in focus state since I have dispatched tab keypress there.

Upvotes: 0

Views: 3484

Answers (1)

Rikhil Arora
Rikhil Arora

Reputation: 118

The reason for this is that your event is not Trusted. isTrusted property of the event is false. This is a readonly property.

More details you can find here JavaScript trigger an InputEvent.isTrusted = true

Upvotes: 1

Related Questions