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.